簡體   English   中英

Python:if雙列表解析中的語句

[英]Python: If statement in double list comprehension

我正在嘗試編寫以下列表理解:

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

列表理解試圖執行以下操作:

  1. 查看writerList中的每個writer
  2. 查看數組中的每個項目[1,2,3]
  3. 如果數組[1,2,3]中的所有項目也存在於writer.solutions中,請考慮編寫者。 否則,丟棄作家。

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

我想我缺乏對如何進行這種雙列表理解的基本理解,其中if依賴於第二種理解。 我很感激在這個問題上閃耀着光芒!

試試這樣:

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

如果writer.solutionsproblems中的項目是可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() )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM