Python - 在列表中搜索另一个列表中的项目

时间:2016-02-02 20:21:28

标签: python

我有一个问题可能很容易,但我无法弄清楚。我有一个清单" l"我想在" q"中查找字符串中的匹配项。如果我搜索一个字符串(如下所示),它将按照预期打印除了慢速棕色狐狸和#34;之外的所有字符串。我无法弄清楚如何循环使用' l'在' q'

中搜索元素
s = '''the quick brown fox
the slow brown fox
the quick red chicken
the quick orange fox'''

l = s.split('\n')

q = ['quick', 'fox']

for i in l:
    if 'quick' in i:
        print(i)

感谢您的帮助。

编辑:我想找到包含' q'。

中的两个项目的字符串

5 个答案:

答案 0 :(得分:2)

for phrase in l:
    if all(word in phrase for word in q):
        print(phrase)

请注意,这与quick中的quickest相符,这可能是您想要的,也可能不是您想要的

答案 1 :(得分:2)

您可以使用设置操作:

>>> set('''the quick brown fox
the slow brown fox
the quick red chicken
the quick orange fox'''.split()).intersection(['quick', 'fox', 'foo'])

{'fox', 'quick'}

[更新]

  

编辑:我想找到包含'q'中两个项目的字符串。

好的,让我再试一次。 : - )

>>> stacks = [_.split() for _ in '''the quick brown fox
the slow brown fox
the quick red chicken
the quick orange fox'''.split('\n')]

>>> needle = ['quick', 'fox']

>>> for stack in stacks:
...     print(stack, set(stack).issuperset(needle))

['the', 'quick', 'brown', 'fox'] True
['the', 'slow', 'brown', 'fox'] False
['the', 'quick', 'red', 'chicken'] False
['the', 'quick', 'orange', 'fox'] True

答案 2 :(得分:2)

根据您的修改,q中的所有字词都必须在该行中:

filter(lambda ll: all(word in ll for word in q), l)

您也可以进行设置操作

q_set = set(q)
for ll in l:
    ll_set = set(ll.split())  # each word
    if q_set <= ll_set:
        print(ll)

答案 3 :(得分:2)

只是为了好玩,这是一种过度优化的方式:

import collections

phrases = collections.defaultdict(list)
for phrase in l:
    for word in phrase.split():
        phrases[word].append(phrase)

for phrase in set.intersection(*[phrases[word] for word in q]):
    print(phrase)

答案 4 :(得分:0)

我的解决方案如下:

import re

s = '''the quick brown fox
the slow brown fox
the quick red chicken
the quick orange fox'''

l = s.split('\n')

q = ['quick', 'fox']


def match_pattern_list_in_string_list(q, l):
    result = []
    for line in l:
        match = True
        for pattern in q:
            if not re.search(pattern, line):
                match = False
        if match:
            result.append(line)
    return result

print match_pattern_list_in_string_list(q, l)

然后它返回:

['the quick brown fox', 'the quick orange fox']
相关问题