All permutations from 2 lists
Antoon Pardon
antoon.pardon at vub.be
Wed Mar 2 09:09:22 EST 2022
Op 2/03/2022 om 14:44 schreef Larry Martell:
> On Wed, Mar 2, 2022 at 8:37 AM Antoon Pardon<antoon.pardon at vub.be> wrote:
>>
>> Op 2/03/2022 om 14:27 schreef Larry Martell:
>>> On Tue, Mar 1, 2022 at 7:21 PM<2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
>>>> On 2022-03-01 at 19:12:10 -0500,
>>>> Larry Martell<larry.martell at gmail.com> wrote:
>>>>
>>>>> If I have 2 lists, e.g.:
>>>>>
>>>>> os = ["Linux","Windows"]
>>>>> region = ["us-east-1", "us-east-2"]
>>>>>
>>>>> How can I get a list of tuples with all possible permutations?
>>>>>
>>>>> So for this example I'd want:
>>>>>
>>>>> [("Linux", "us-east-1"), ("Linux", "us-east-2"), ("Windows",
>>>>> "us-east-1"), "Windows", "us-east-2')]
>>>>>
>>>>> The lists can be different lengths or can be 0 length. Tried a few
>>>>> different things with itertools but have not got just what I need.
>>>> [(o, r) for o in os for r in region]
>>> This does not work if region = []. I wrote in my question that either
>>> list could be empty.
>> What do you mean it doesn't work? The result seems to be an empty list,
>> which IMO is a perfectly valid result.
>>
>> All possible permutations over two collections where one collection is
>> empty, should IMO give you an empty collection.
> If one list is empty I want just the other list. What I am doing is
> building a list to pass to a mongodb query. If region is empty then I
> want to query for just the items in the os list. I guess I can test
> for the lists being empty, but I'd like a solution that handles that
> as down the road there could be more than just 2 lists.
How about the following: Keep a list of your lists you want to permute over.
Like the following:
permutation_elements = [["Linux","Windows"],["us-east-1", "us-east-2"]]
permutation = itertools.product(*permutation_elements)
If you don't include the empty list, you will get more or less what you
seem to want.
Antoon Pardon.
More information about the Python-list
mailing list