我有一些列表,我想从中过滤元素。这是列表:
list1 = ['Little Mary had a lamb', 'the horse is black', 'Mary had a cat']
list2 = ['The horse is white', 'Mary had a dog', 'The horse is hungry']
listn = ...
在以下示例中,假设我知道一个相关的单词或表达, Mary 或 horse 。我想获得一个新列表,如果这些项包含术语或搜索的表达式,将从其他列表中提取哪些项。 例如。 :
listMary = ['Little Mary had a lamb', 'Mary had a cat', 'Mary had a dog']
listHorse = ['the horse is black', 'The horse is white', 'The horse is hungry']
listn = ...
不要担心我的数据更复杂;)
我知道我应该使用正则表达式模块,但在这种情况下我无法找到以哪种方式。我在Stack Overflow上尝试了一些搜索,但我不知道如何清楚地表达问题所以我找不到任何有用的东西。
答案 0 :(得分:2)
可能是这样的:
>>> a = ['Little Mary had a lamb', 'the horse is black', 'Mary had a cat']
>>> b = ['The horse is white', 'Mary had a dog', 'The horse is hungry']
>>> [sent for sent in a+b if 'Mary' in sent]
['Little Mary had a lamb', 'Mary had a cat', 'Mary had a dog']
或者如果您更喜欢使用正则表达式:
>>> import re
>>> [sent for sent in a+b if re.search("horse", sent)]
['the horse is black', 'The horse is white', 'The horse is hungry']
答案 1 :(得分:0)
使用列表推导的条件子句。
[x for x in L if regex.search(x)]
答案 2 :(得分:0)
您不一定需要正则表达式模块:
word = 'horse'
result = []
for l in [list1, list2, list3]:
for sentence in l:
if word in sentence:
result.append(sentence)
答案 3 :(得分:0)
用户内置函数filter
它将快速有效。
def f(x):
return x % 2 != 0 and x % 3 != 0
filter(f, range(2, 25))
所以这里def f将需要一个arg并进行匹配并返回true false并且您将获得结果列表。
谢谢