具有两个"fors"和"if"条件的列表理解

opt*_*ime 1 python list-comprehension

我有2个清单:

>>> phrases = ['emp_sal','emp_addr']
>>> cols = ['emp_sal_total','emp_sal_monthly','emp_addr_primary','emp_ssn','emp_phone']
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用列表推导并过滤掉cols,以便只选择cols中的那些值,其中包含短语emp_salemp_addr.

所以,输出应该是:

['emp_sal_total','emp_sal_monthly','emp_addr_primary']
Run Code Online (Sandbox Code Playgroud)

这只是复制场景的一个虚拟示例.实际例子具有COLS 180的奇数列的列表.

尝试下面的解决方案:

new_cols = [c for c in cols if p for p in phrases in c]
Run Code Online (Sandbox Code Playgroud)

它失败了:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
Run Code Online (Sandbox Code Playgroud)

以下方法产生一个空白列表:

  >>> [c for c in cols if p in c for p in phrases]
   []
Run Code Online (Sandbox Code Playgroud)

Chr*_*ean 5

您需要测试短语中的任何字符串是否在您迭代的当前列中cols.为此,请使用any():

[c for c in cols if any(c.startswith(p) for p in phrases)]
Run Code Online (Sandbox Code Playgroud)

您的方法的问题是您p在定义之前尝试使用,这会引发NameError:

>>> [c for c in cols if p in c for p in phrases]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'p' is not defined
Run Code Online (Sandbox Code Playgroud)

正如@Hamms的评论中所述,您仍然可以使用与您的方法类似的东西.p在尝试使用它之前,您只需要定义:

>>> [c for c in cols for p in phrases if p in c]
['emp_sal_total', 'emp_sal_monthly', 'emp_addr_primary']
>>> 
Run Code Online (Sandbox Code Playgroud)