比较 python 中的字符串的嵌套列表理解理解

Nested list comprehension understanding for comparing strings in python

我有两个列表

l1 = ["filea", "fileb", "filec"]
l2 = ["a", "b"]

我想生成一个结果列表 l3,其中包含 l1 的元素,而 l1 的元素又包含 l2 的元素。所以最后我想要

l3 = ["filea", "fileb"]

我只是不知道如何使用列表推导来做到这一点... 我试过了:

l3 = [x for x in l1 for y in l2 if y in x]

而且有效...

我只想了解这里真正发生的事情以及发生的顺序。如有任何帮助,我将不胜感激!

同样可以写成:

l3 = []
for x in l1:
    for y in l2:
        if y in x:
            l3.append(x)

您可以简单地循环所有列表并检查 l2 中是否有一个元素位于 l1 个元素中

例子

l1 = ["filea", "fileb", "filec"]
l2 = ["a", "b"]

l3 = list({x for x in l1 for y in l2 if x[-1] in l2})
# Or
l3 = [x for x in l1 for y in l2 if y in x]
print(l3)

列表理解分解

你只是遍历了 l1l2 因为在 python 中你可以像在列表中一样对字符串进行索引并且你还可以检查整个字符串中是否出现了一个字符你在 if y in x 上所做的也是如此 你检查字符 y 是否出现在字符串 x

l3 = []
for x in l1:
    for y in l2:
        if y in x:
            l3.append(x)

输出

['filea', 'fileb']

当你写:

l3 = [x for x in l1 for y in l2 if y in x]

等于:

l3 = []
for x in l1:  # loop through each element in the list l1
    for y in l2:  # loop through each element in the list l2
        if y in x: # if x contains y
            l3.append(x)

你可以

l3 = [s for s in l1 if any(c in s for c in l2)]

更有效的解决方案是使用正则表达式:

import re
pattern = re.compile('|'.join(map(re.escape, l2)))
l3 = list(filter(pattern.search, l1))   # Equivalent to [s for s in l1 if pattern.search(s)]