在Python中比较两个列表时匹配字符串

时间:2020-09-11 08:36:56

标签: python

我试图匹配两个列表中相似的字符串,如果匹配则结果为True。到目前为止,我只尝试False进行理解并设置交叉点,结果是相同的。

我现在所拥有的:

a = ['The weather today is awful', 'Last night I had a bad dream']

b = ['The weather today is awful and tomorow it will be probably the same', 'Last night I had a bad dream about aliens']

match = any([item in a for item in b])
print(match)

所以我想做的是将列表The weather today is awful中的a与列表b的句子匹配,将Last night I had a bad dream与列表{{1}的句子匹配}等...

4 个答案:

答案 0 :(得分:2)

您需要类似的东西

match = any(ia in ib for ia in a for ib in b)

或者,使用itertools.product

from itertools import product

match = any(ia in ib for ia, ib in product(a, b))

答案 1 :(得分:1)

通过检查b中的任何项是否在列表a中,而不是a中的字符串,您仍在比较完整字符串(向后)。

any(item in x for x in b for item in a)

我假设您要检查a中的任何字符串是否在列表b中的字符串之内

答案 2 :(得分:1)

如果要将a中的每个项目与b中的任何项目进行匹配,则可以执行以下操作:

[any(item in item2 for item2 in b) for item in a]

如果只想将a中的每个项目与b中的项目在对应的索引处进行匹配,则可以执行以下操作:

[item in item2 for item, item2 in zip(a,b)]

上述两个示例均返回[True, True]

a = ['The weather today is awful', 'Last night I had a bad dream']

b = ['The weather today is awful and tomorow it will be probably the same', 'Last night I had a bad dream about aliens']

但是例如,如果您颠倒了b的顺序:

b = b[::-1]

然后第一个表达式wouold仍然返回[True, True],而第二个表达式现在返回[False, False]-换句话说,a的第一个元素现在包含在b的一个元素而不是第一个元素,并且类似地,a的第二个元素现在包含在b an 元素中第二个。

如果您只是对a中的任何项目或b中的任何项目中包含b中的任何项目感兴趣,请使用这些列表推导(或更好的类似生成器表达式)作为对any的输入。例如:

any(any(item in item2 for item2 in b) for item in a)

测试a中的任何项目是否包含在b中的任何项目中

any(item in item2 for item, item2 in zip(a,b))

测试a中的任何项目是否包含在b

中的相应项目

答案 3 :(得分:0)

您可以将any()startswith()结合使用以实现结果,而无需导入任何内容:

a = ['The weather today is awful', 'Last night I had a bad dream']

b = ['The weather today is awful and tomorow it will be probably the same', 'Last night I had a bad dream about aliens']

print(any([item2.startswith(item1) for item1, item2 in zip(a, b)])) # True