繁体   English   中英

比较字符串列表的最快方法

[英]Fastest way of comparing lists of strings

A = ['a','b','c'] 
B = ['d','b','e']

res = [i for i in A if i in B]

当A中的元素数为300000且B中的元素数为200000时,以上代码不起作用。

我该如何解决?

我也试过

res = {i for i in A if i in B}
res = list(res)

但是仍然无法得到结果。

A = ['a','b','c']
B = ['d','b','e']

set(A).intersection(B)

要获取返回的列表:

list(set(A).intersection(B))

相交将任何可迭代项作为参数,因此您只需将A设为集合。

请注意,union(),intersection(),difference()和symmetric_difference()的非运算符版本将接受任何可迭代的参数。

如果保留顺序和/或重复项无关紧要,则可以使用

A = ['a', 'b', 'c']
B = ['d', 'e', 'f']
res = list(set(A) & set(B))

如果顺序和/或重复项很重要,则可以使用

A = ['a', 'b', 'c']
B = ['d', 'e', 'f']
set_b = set(B)
res = [i for i in A if i in set_b]

您基本上是在计算两个集合的交集。 为此,使用set数据类型将使其高效:

A = {'a','b','c'}
B = {'d','b','e'}
res = A & B

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM