[英]Count the number of unique elements of a list of tuples regardless of order in Python
[英]Get count of tuples in list regardless of elements orders
我有一个元组列表,看起来像这样:
my_list = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
无论顺序如何,我都希望对数字组合进行计数。 例如,如果要简单地打印,我希望输出为:
1,12 = 3
20,15 = 2
7,8 = 1
基本上,我有一个连接列表,但方向无关紧要,因此1到12与12到1相同。
我已经为此工作了一段时间,无法提出一个干净的解决方案。 我想出的一切都必须检查两个方向,但是元组的列表是随机的,因此涵盖所有可能性将是荒谬的。 我可以轻松地用set或其他东西来计算唯一的元组,但是同样,我想到的“双向”计数的每个解决方案都是草率的。
我觉得这不应该很困难,但是我花了这么长时间来研究,对此我感到很头疼。 任何帮助将不胜感激!
您可以使用collections.Counter
,与您的正常化元素sorted
第一。
from collections import Counter
lst = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
count = Counter(tuple(sorted(t)) for t in lst)
# output: Counter({(1, 12): 3, (15, 20): 2, (7, 8): 1})
然后可以像这样打印。
for value, amount in count.items():
print(value, '=', amount)
# Prints:
# (1, 12) = 3
# (15, 20) = 2
# (7, 8) = 1
首先,您可以对列表进行排序
lst2 = [tuple(sorted(i)) for i in lst]
然后,您可以使用set()
在此列表中查找唯一值并计算它们的出现次数。
count = {}
for i in set(lst2):
num = len([1 for j in lst2 if j == i])
count.update({i:num})
print(count)
{(1,12):3,(7,8):1,(15,20):2}
您可以尝试简单的方法,而无需导入如下内容:
my_list = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
count={}
for i in my_list:
if tuple(sorted(i)) not in count:
count[tuple(sorted(i))]=1
else:
count[tuple(sorted(i))]+=1
print(count)
输出:
{(15, 20): 2, (7, 8): 1, (1, 12): 3}
您可以按大小交换所有头寸,然后使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.