[英]How to calculate the difference between the elements in three lists efficiently?
我有3个非常大的字符串列表,出于可视化目的考虑:
A = ['one','four', 'nine']
B = ['three','four','six','five']
C = ['four','five','one','eleven']
我如何计算此列表之间的差异,以便仅获取其他列表中未重复的元素。 例如:
A = ['nine']
B = ['three','six']
C = ['eleven']
方法1
您只需更改第一行即可任意添加更多列表,例如my_lists = (A, B, C, D, E)
。
my_lists = (A, B, C)
my_sets = {n: set(my_list) for n, my_list in enumerate(my_lists)}
my_unique_lists = tuple(
list(my_sets[n].difference(*(my_sets[i] for i in range(len(my_sets)) if i != n)))
for n in range(len(my_sets)))
>>> my_unique_lists
(['nine'], ['six', 'three'], ['eleven'])
my_sets
使用字典理解来为每个列表创建集合。 字典的关键是my_lists
的列表顺序排名。
然后将每个集合与字典中的所有其他集合区别(禁止),然后转换回列表。
的排序my_unique_lists
对应于排序my_lists
。
方法2
您可以使用Counter
获得所有唯一项(即仅出现在一个列表中而不显示在其他列表中的项),然后使用列表推导来遍历每个列表并选择唯一的项。
from collections import Counter
c = Counter([item for my_list in my_lists for item in set(my_list)])
unique_items = tuple(item for item, count in c.items() if count == 1)
>>> tuple([item for item in my_list if item in unique_items] for my_list in my_lists)
(['nine'], ['three', 'six'], ['eleven'])
A, B, C = map(set, (A, B, C))
a = A - B - C
b = B - A - C
c = C - A - B
A, B, C = map(list, (a, b, c))
(可能的)问题是最终列表不再排序,例如
>>> A
['nine']
>>> B
['six', 'three']
>>> C
['eleven']
可以通过按原始索引进行排序来解决此问题,但是时间复杂度将急剧增加,因此使用集合的好处几乎完全丧失了。
sA, sB, sC = map(set, (A, B, C))
A = [e for e in A if e not in sB and e not in sC]
B = [e for e in B if e not in sA and e not in sC]
C = [e for e in C if e not in sA and e not in sB]
然后产生一个保持列表原始顺序的结果:
>>> A
['nine']
>>> B
['three', 'six']
>>> C
['eleven']
总之,如果您不关心结果的顺序,可以将列表转换为集合,然后采用它们之间的差异(而不用费心转换回列表)。 但是,如果您确实关心顺序,则仍将列表转换为集合(哈希表),因为过滤它们时查找仍会更快(列表的最佳情况为O(1)
与O(n)
)。
您可以遍历所有列表元素,并添加当前元素以设置当前元素(如果不存在),以及将其从列表中删除。 这样,您将使用高达O(n)的空间复杂度和O(n)的时间复杂度,但元素将保持有序。
您也可以使用功能定义来检查三个列表之间的差异。 这是此类函数的示例:
def three_list_difference(l1, l2, l3):
lst = []
for i in l1:
if not(i in l2 or i in l3):
lst.append(i)
return lst
函数three_list_difference
获取三个列表,并检查第一个列表l1
的元素是否也在l2
或l3
。 可以通过在正确的配置中简单调用该函数来确定是否遵循:
three_list_difference(A, B, C)
three_list_difference(B, A, C)
three_list_difference(C, B, A)
输出:
['nine']
['three', 'six']
['eleven']
使用函数是有利的,因为代码是可重用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.