2014-11-05 85 views
1

我可以評估列表理解中的bool嗎?python在列表理解中評估bool

我想創建一個不包含與'.zip'最終產品列表:

outlist = [x for x in os.listdir(path) if x *DOES NOT* end with '.zip'] 

我用列表修真正好相反:

outlist2 = [x for x in os.listdir(path) if x.endswith('.zip')] 

這裏是outout我的清單

os.listdir(path): 
[ 
'sample1.zip', 'sample2.zip', 'sample3.zip', 'sample4.zip', 
'sample1.txt', 'sample2.pdf', 'sample3.csv', 'sample4.xlsx' 
] 

回答

0

只需添加not

outlist2 = [x for x in os.listdir(path) if not x.endswith('.zip')] 

if表達可以是任何有效的Python表達式,包括使用布爾運算符之一。

演示:

>>> sample = ['sample1.zip', 'sample2.zip', 'sample3.zip', 'sample4.zip', 
...   'sample1.txt', 'sample2.pdf', 'sample3.csv', 'sample4.xlsx'] 
>>> [x for x in sample if not x.endswith('.zip')] 
['sample1.txt', 'sample2.pdf', 'sample3.csv', 'sample4.xlsx'] 
0

當然,你可以 - 只是巴掌not運營商有:

outlist2 = [x for x in os.listdir(path) if not x.endswith('.zip')]