2017-07-25 140 views
1

我有2所列出:列表理解兩個「維權」和「如果」條件

>>> phrases = ['emp_sal','emp_addr'] 
>>> cols = ['emp_sal_total','emp_sal_monthly','emp_addr_primary','emp_ssn','emp_phone'] 

我試圖使用列表理解並篩選出的cols這樣,只有在的cols這些值應該挑選出來,其中包含一個短語emp_salemp_addr

因此,輸出應該是:

['emp_sal_total','emp_sal_monthly','emp_addr_primary'] 

這只是一個虛擬的例子複製的場景。實際示例具有180個奇數列的cols列表。

嘗試以下解決方案:

new_cols = [c for c in cols if p for p in phrases in c] 

它失敗:

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

以下方法產生一個空白列表:

>>> [c for c in cols if p in c for p in phrases] 
    [] 
+0

我想你想'[C對C中的cols的p在短語如果p在C]' – Hamms

+0

這工作得很好。有點接近.. :) –

回答

5

您需要測試如果短語任何字符串在當前列中,您在cols中迭代。對於這一點,使用any()

[c for c in cols if any(c.startswith(p) for p in phrases)] 

與方法的問題是,你試圖使用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 

正如在評論中指出@哈姆斯,你仍然可以使用類似於你的方法的東西。你只需要在嘗試使用它之前已經定義p

>>> [c for c in cols for p in phrases if p in c] 
['emp_sal_total', 'emp_sal_monthly', 'emp_addr_primary'] 
>>>