简体   繁体   中英

Python: If statement in double list comprehension

I'm attempting to write the following list comprehension:

[writer for writer in writerList if problem in writer.solutions for problem in [1,2,3]]

The list comprehension is attempting to perform the following:

  1. Look through each writer in writerList
  2. Look through each item in the array [1,2,3]
  3. If all the items in the array [1,2,3] are also present in writer.solutions, consider the writer. Else, discard the writer.

However, using the above list comprehension I am told that the local variable problem is referenced before assignment.

I suppose I am lacking a fundamental understanding of how to do this kind of double list comprehension where the if relies on the second comprehension. I would appreciate any light shined on the issue!

试试这样:

[writer for writer in writerList  for problem in [1,2,3] if problem in writer.solutions]

This specific problem could possibly be optimized and simplified by using sets if the items in writer.solutions and problems are hashable (the integers you provide in your example are hashable, mutable items like dictionaries and lists aren't).

problems = set([1, 2, 3])
writers = [writer for writer in writerList if not problems.difference(writer.solutions)]

set.difference(other) will return items in the set that aren't in the other. So, if all the items in your problem set are in writer.solutions , the it will return an empty set, which evaluates to False (hence the not set.difference() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM