[英]Python list comprehension logic error
我正在嘗試使用正則表達式和列表理解清除包含"msi"
的字符串。 但是,當我打印列表時,包含"msi"
的字符串仍在列表中。 錯誤究竟是什么? 這是我的代碼:
spam_list = [l for l in spam_list if not re.match("msi", l)]
re.match()
從字符串的開頭匹配。 使用re.search()
,甚至更好, in
.
L = [l for l in L if "msi" not in l]
由於您顯然是在查看文件名列表,因此您也可以使用 endwith:
list = [l for l in list if l.endswith('.msi')]
這是按文件擴展名過濾列表的一種方法
import os
extensions = set(['.msi', '.jpg', '.exe'])
L = [l for l in L if os.path.splitext(l)[1] not in extensions]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.