清单的理解和条件? [英] List Comprehensions and Conditions?
问题描述
我正在尝试看看是否可以使用列表理解来使此代码更好.
可以说我有以下列表:
I am trying to see if I can make this code better using list comprehensions.
Lets say that I have the following lists:
a_list = [
'HELLO',
'FOO',
'FO1BAR',
'ROOBAR',
'SHOEBAR'
]
regex_list = [lambda x: re.search(r'FOO', x, re.IGNORECASE),
lambda x: re.search(r'RO', x, re.IGNORECASE)]
我基本上想将regex_list
中没有任何匹配项的所有元素添加到另一个列表中.
I basically want to add all the elements that do not have any matches in the regex_list
into another list.
例如==>
newlist = []
for each in a_list:
for regex in regex_list:
if(regex(each) == None):
newlist.append(each)
如何使用列表推导来做到这一点?甚至有可能吗?
How can I do this using list comprehensions? Is it even possible?
推荐答案
当然,我认为应该这样做
Sure, I think this should do it
newlist = [s for s in a_list if not any(r(s) for r in regex_list)]
EDIT :经过仔细检查,我注意到您的示例代码实际上将a_list
中与正则表达式 all 不匹配的每个字符串添加到新列表中-而且,它为每个不匹配的正则表达式添加一次每个字符串.我的列表理解功能符合我的意思,即为每个与正则表达式任何不匹配的字符串添加一个副本.
EDIT: on closer inspection, I notice that your example code actually adds to the new list each string in a_list
that doesn't match all the regexes - and what's more, it adds each string once for each regex that it doesn't match. My list comprehension does what I think you meant, which is add only one copy of each string that doesn't match any of the regexes.
这篇关于清单的理解和条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!