简体   繁体   English

如何在python中有效地比较两个集合列表?

[英]How to compare two list of sets effectively in python?

I have a list of sets:我有一个集合列表:

list = [{1,2}, {2,3}, {1,3}, {2,1} etc]

I need a list where every element appears once.我需要一个列表,其中每个元素都出现一次。 creating a set of the list fails with a set is not hashable error If I create another list, and add every element once with if not in list then append list works, but now I have to deal with a list with aroun 600 000 value pairs, and it takes forever.创建一组列表失败,出现一个 set is not hashable 错误如果我创建另一个列表,并使用 if not in list 添加每个元素一次,然后追加列表有效,但现在我必须处理一个包含大约 600 000 个值对的列表,而且需要永远。 Is there a more efficent way?有没有更有效的方法?

Referencing your comment;引用您的评论; as you mentioned this worked, I'll post my comment as a proper answer.正如您所提到的,这行得通,我会将我的评论作为正确答案发布。

set(map(tuple, list_))

Output:输出:

{(1, 2), (1, 3), (2, 3)}

Please note:请注意:
I've changed the your list variable named to list_ , as it was overwriting the built-in.我已将您的list变量命名为list_ ,因为它覆盖了内置变量。

This method appears to scale linearly.这种方法似乎是线性缩放的。 Time over a list of 1000 sets was 206 us and 10000 was 2.19 ms. 1000 组列表的时间为 206 us,10000 为 2.19 ms。

You can use the following method to perform a union on a list of set:您可以使用以下方法对集合列表执行联合:

l = [{1,2}, {2,3}, {1,3}, {2,1}]
set.union(*l)

output:输出:

{1, 2, 3}

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

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