将“唯一对”的数字计数到Python字典中?

Sha*_*ang 0 python dictionary nested-lists python-itertools python-3.x

编辑:编辑错别字;字典的键值应该是字典,而不是集合。

不过,我会在这里保留拼写错误,因为下面的问题解决了这个问题。对于造成的混乱,我深表歉意。

问题是这样的:

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

list1 = [2, 3]   
Run Code Online (Sandbox Code Playgroud)

在这种情况下,有一个唯一的对 2-3 和 3-2,所以字典应该是:

{2:{3: 1}, 3:{2: 1}}
Run Code Online (Sandbox Code Playgroud)

即有1对2-3和1对3-2。

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

list2 = [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

有词典

{2:{3: 1}, 3:{2: 1}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}}
Run Code Online (Sandbox Code Playgroud)

(1) 一旦列表的大小变得很大,如何使用 python 数据结构通过算法找到这种格式的“唯一对”?

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

[2, 2, 3]
Run Code Online (Sandbox Code Playgroud)

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

然而,人们可能有一系列的列表:

list3 = [[2, 3], [2, 3, 4]] 
Run Code Online (Sandbox Code Playgroud)

因此字典必须是

{2:{3: 2}, 3:{2: 2}, 3:{4: 1}, 4:{3: 1}, 2:{4: 1}, 4:{2: 1}}
Run Code Online (Sandbox Code Playgroud)

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

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

Oli*_*çon 7

您想要的是计算列表中组合产生的对的数量。您可以找到带有Counter和的那些combinations

from itertools import combinations
from collections import Counter

list2 = [2, 3, 4]

count = Counter(combinations(list2, 2))

print(count)
Run Code Online (Sandbox Code Playgroud)

输出

Counter({(2, 3): 1, (2, 4): 1, (3, 4): 1})
Run Code Online (Sandbox Code Playgroud)

至于您的列表列表,我们会Counter使用每个子列表的结果进行更新。

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)
Run Code Online (Sandbox Code Playgroud)

输出

Counter({(2, 3): 2, (2, 4): 1, (3, 4): 1})
Run Code Online (Sandbox Code Playgroud)