Home > Enterprise >  is there a way to self reference within a list generation in python
is there a way to self reference within a list generation in python

Time:06-02

I want to create the following list of tuples of strings:

pairs = [(s1,s2) for s1 in S for s2 in S if s1 != s2 and (s2,s1) not in self]

Obviously not in self doesn't work. Is there a way to achieve this with a generator expression? Thanks

CodePudding user response:

You don't want a list, you want a set:

pairs = {(s1,s2) for s1 in S for s2 in S if s1 != s2}

Sets can only have a single element of a given (hashable) value. Your self-referential filter clause (not in self) is essentially asking to ensure that there is only one such element, which is what a set is for. You can easily list(pairs) after this if you need a list instead of a set for what you're doing.

A downside of this is that the values must be hashable (immutable values, or mutable values that can be hashed).

CodePudding user response:

No, there's no way to reference the object being constructed by a comprehension.

Do it in two steps: First create the list, then add to the list in a loop.

pairs = []
for s1 in S:
    for s2 in S:
        if (s1, s2) not in pairs:
            pairs.append((s1, s2))
  • Related