[英]Python list comprehension logic error
I'm trying to weed out strings that contains "msi"
using regular expressions and a list comprehension.我正在尝试使用正则表达式和列表理解清除包含
"msi"
的字符串。 However, when I print the list, strings that contain "msi"
are still in the list.但是,当我打印列表时,包含
"msi"
的字符串仍在列表中。 What exactly would the error be?错误究竟是什么? This is my code:
这是我的代码:
spam_list = [l for l in spam_list if not re.match("msi", l)]
re.match()
matches from the beginning of the string. re.match()
从字符串的开头匹配。 Use re.search()
, or even better, in
.使用
re.search()
,甚至更好, in
.
L = [l for l in L if "msi" not in l]
Since you're apparently looking through a list of filenames, you could also use endswith:由于您显然是在查看文件名列表,因此您也可以使用 endwith:
list = [l for l in list if l.endswith('.msi')]
Here is one way to filter a list by the file extension这是按文件扩展名过滤列表的一种方法
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.