获取列表中的元组数,而与元素顺序无关 [英] Get count of tuples in list regardless of elements orders
问题描述
我有一个看起来像这样的元组列表:
I have a list of tuples that looks something like this:
my_list = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
无论顺序如何,我都希望对数字组合进行计数.例如,如果要简单打印,我希望输出为:
I want to get a count of the number combinations regardless of the order. For example, if it were to be simply printed, I'd like the output to be:
1,12 = 3
20,15 = 2
7,8 = 1
基本上,我有一个连接列表,但方向无关紧要,所以1到12与12到1相同.
Basically, I have a list of connections but the direction doesn't matter, so 1 to 12 is the same as 12 to 1.
我已经为此工作了一段时间,无法提出一个干净的解决方案.我想出的一切都必须检查两个方向,但是元组的列表是随机的,因此涵盖所有可能性将是荒谬的.我可以很容易地用set或其他东西来计算唯一的元组,但是同样,我想到的双向"计数的每个解决方案都是草率的.
I have been working on this for a while and can't come up with a clean solution. Everything I've come up with would have to check for both directions, but the list of tuples is random, so covering every possibility would be ridiculous. I could easily count the unique tuples with set or something, but again, every solution for the "bi-directional" count I've thought about is sloppy.
我觉得这应该不是很难,但是我花了这么长时间来研究,对此我感到非常困惑.任何帮助将不胜感激!
I feel like this shouldn't be very hard, but I am thoroughly at brain fry from working on this so long. Any help would be greatly appreciated!
推荐答案
您可以按大小交换所有职位,然后使用collections.counter
:
You can swap all positions by size and then use collections.counter
:
from collections import Counter
l = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
new_l = Counter([[(b, a), (a, b)][a < b] for a, b in l])
for a, b in new_l.items():
print('{},{}:{}'.format(*(list(a)+[b])))
输出:
15,20:2
7,8:1
1,12:3
这篇关于获取列表中的元组数,而与元素顺序无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!