对“唯一对”进行计数。数到python字典中? [英] Counting "unique pairs" of numbers into a python dictionary?

查看:98
本文介绍了对“唯一对”进行计数。数到python字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:编辑错别字;

我会在这里保留输入错误,因为下面的问题解决了这个问题。我为此感到抱歉。

I will keep the typos here though, as the questions below address this question. My apologies for the confusion.

这是问题所在:

假设我有一个整数列表,其中永远不会重复:

Let's say I have a list of integers whereby are never repeats:

list1 = [2, 3]   

在这种情况下,存在一对2-3和3-2唯一,因此字典应为:

In this case, there is a unique pair 2-3 and 3-2, so the dictionary should be:

{2:{3: 1}, 3:{2: 1}}

也就是说,有1对2-3和1对3-2。

That is, there is 1 pair of 2-3 and 1 pair of 3-2.

对于较大的列表,配对是相同的,例如

For larger lists, the pairing is the same, e.g.

list2 = [2, 3, 4]

具有二分法

{2:{3: 1}, 3:{2: 1}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}}

(1)列表变得越来越大,一个人如何使用python数据结构以算法找到这种格式的唯一对?

(1) Once the size of the lists become far larger, how would one algorithmically find the "unique pairs" in this format using python data structures?

(2)我提到列表不能重复整数,例如

(2) I mentioned that the lists cannot have repeat integers, e.g.

[2, 2, 3]

是不可能的,因为有两个2。

is impossible, as there are two 2s.

但是,可能会有一个列表列表:

However, one may have a list of lists:

list3 = [[2, 3], [2, 3, 4]] 

其中字典必须是

{2:{3: 2}, 3:{2: 2}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}}



<因为有两对2-3和3-2。给定一个列表中的多个列表,如何更新字典?

as there are two pairs of 2-3 and 3-2. How would one "update" the dictionary given multiple lists within a list?

这是一个算法问题,我不知道最有效的解决方案。我的想法是以某种方式将值缓存在列表中并枚举对……但这太慢了。我猜测 itertools 有一些有用的东西。

This is an algorithmic problem, and I don't know of the most efficient solution. My idea would be to somehow cache values in a list and enumerate pairs...but that would be so slow. I'm guessing there's something useful from itertools.

推荐答案

想要的是对列表中组合产生的对进行计数。您可以找到带有计数器组合的那些。

What you want is to count pairs that arise from combinations in your lists. You can find those with a Counter and combinations.

from itertools import combinations
from collections import Counter

list2 = [2, 3, 4]

count = Counter(combinations(list2, 2))

print(count)



输出



Output

Counter({(2, 3): 1, (2, 4): 1, (3, 4): 1})

至于您的列表列表,我们更新了 Counter 以及每个子列表的结果。

As for your list of list, we update the Counter with the result from each sublist.

from itertools import combinations
from collections import Counter

list3 = [[2, 3], [2, 3, 4]]

count = Counter()

for sublist in list3:
    count.update(Counter(combinations(sublist, 2)))

print(count)



输出



Output

Counter({(2, 3): 2, (2, 4): 1, (3, 4): 1})

这篇关于对“唯一对”进行计数。数到python字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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