当子列表的顺序无关紧要时,从列表列表中获取唯一元素 [英] Get unique elements from list of lists when the order of the sublists does not matter

查看:77
本文介绍了当子列表的顺序无关紧要时,从列表列表中获取唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个成对的列表,表示图中簇的所有边.实际上列表比这大.这只是一个例子.

I have a list of pairs, representing all edges of cluster in a graph. Actually the list is bigger than this. This is just an example.

[[1, 2], [2, 1], [3, 5], [6, 3], [3, 6]]

[1, 2]表示节点1和2之间的边,[2, 1]也是如此. 因此,我很难消除重复的对以计算聚类的度数.

[1, 2] means an edge between nodes 1 and 2, and so does [2, 1]. So, I have some difficulty to eliminate the repeated pairs to count the in-degrees of the cluster.

输出应类似于[[1, 2], [3, 5], [3, 6]][[2, 1], [3, 5], [6, 3]]

推荐答案

如果对的元素顺序无关紧要,请使用sorted来标准化对.然后,使用set消除重复项.

If order of the pairs' elements is irrelevant, then use sorted to normalize pairs. Then, use a set to eliminate duplicates.

lst = [1, 2], [2, 1], [3, 5], [6, 3], [3, 6]

unique_pairs = {tuple(sorted(p)) for p in lst} # {(1, 2), (3, 6), (3, 5)}

这篇关于当子列表的顺序无关紧要时,从列表列表中获取唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆