Python:如果双列表理解中的语句(Python: If statement in double list comprehension)

编程入门 行业动态 更新时间:2024-10-13 00:31:12
Python:如果双列表理解中的语句(Python: If statement in double list comprehension)

我正在尝试编写以下列表理解:

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

列表理解试图执行以下操作:

查看writerList中的每个writer 查看数组中的每个项目[1,2,3] 如果数组[1,2,3]中的所有项目也存在于writer.solutions中,请考虑编写者。 否则,丢弃作者。

但是,使用上面的列表理解我被告知在赋值之前引用局部变量problem 。

我想我缺乏对如何进行这种双列表理解的基本理解,其中if依赖于第二种理解。 我很感激任何关于这个问题的光芒!

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:

Look through each writer in writerList Look through each item in the array [1,2,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.solutions和problems中的项目是可writer.solutions (在您的示例中提供的整数是可清除的,可变项目,如字典和列表不是),则可以通过使用sets来优化和简化此特定问题。

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

set.difference(other)将返回集合中不在另一个中的项目。 因此,如果您的问题集中的所有项都在writer.solutions ,它将返回一个空集,其计算结果为False(因此not set.difference() )。

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()).

更多推荐

本文发布于:2023-07-14 18:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1106699.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   列表   Python   statement   comprehension

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!