1

我有一些列表,我想从中过滤元素。这是列表:

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 = ...

假设我知道一个相关的单词或表达方式,下例中的Maryhorse。如果这些项目包含搜索的术语或表达式,我想获得一个新列表,哪些项目将从其他列表中提取。例如:

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 上尝试了一些搜索,但我不知道如何足够清楚地表述问题,所以我找不到任何有用的东西。

4

4 回答 4

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']
于 2012-06-20T07:25:52.167 回答
0

使用列表推导式的条件子句。

[x for x in L if regex.search(x)]
于 2012-06-20T06:32:07.150 回答
0

您不一定需要正则表达式模块:

word = 'horse'
result = []
for l in [list1, list2, list3]:
    for sentence in l:
        if word in sentence:
            result.append(sentence)
于 2012-06-20T06:34:12.193 回答
0

用户内置功能filter ,它将快速高效。

def f(x): 
    return x % 2 != 0 and x % 3 != 0

filter(f, range(2, 25))

所以这里 def f 将采用一个 arg 并进行匹配并返回 true false ,您将获得结果列表。

谢谢你

于 2012-06-20T06:58:36.097 回答