All permutations from 2 lists

Larry Martell larry.martell at gmail.com
Wed Mar 2 10:49:11 EST 2022


On Wed, Mar 2, 2022 at 10:26 AM Antoon Pardon <antoon.pardon at vub.be> wrote:
>
>
>
> Op 2/03/2022 om 15:58 schreef Larry Martell:
> > On Wed, Mar 2, 2022 at 9:37 AM Antoon Pardon<antoon.pardon at vub.be>  wrote:
> >>
> >>>>> 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.
> >>> But I need to deal with that case.
> >> What does that mean? How does using the above method to produce the permutations
> >> you want, prevent you from dealing with an empty list however you want when you
> >> encounter them? Just don't add them to the permutation_elements.
> > I need to know what items are in which position. If sometimes the
> > regions are in one index and sometimes in another will not work for
> > me.
>
> I am starting to suspect you didn't think this through. What you are telling here
> contradicts what you told earlier that if either list was empty, you just wanted
> the other list. Because then you wouldn't know what items were in that list.
>
> The only solution I can see now is that if a list is empty, you either add [None] or
> [""] to the permutation_elements (whatever suits you better) and then use
> itertools.product

I found a way to pass this directly into the query:

def query_lfixer(query):
    for k, v in query.items():
        if type(v)==list:
            query[k] = {"$in": v}
    return query

self._db_conn[collection_name].find(query_lfixer(query))


More information about the Python-list mailing list