簡體   English   中英

將數字的“唯一對”計數到python字典中?

[英]Counting “unique pairs” of numbers into a python dictionary?

編輯:編輯錯別字; 字典的鍵值應該是字典,而不是集合。

我將在這里保留輸入錯誤,因為以下問題解決了這個問題。 對於造成混亂,我深表歉意。

這是問題所在:

假設我有一個整數列表,其中永不重復:

list1 = [2, 3]   

在這種情況下,存在唯一的一對2-3和3-2,因此字典應為:

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

即,存在一對2-3和1對3-2。

對於較大的列表,配對是相同的,例如

list2 = [2, 3, 4]

具有二分法

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

(1)一旦列表的大小變得更大,一個人如何使用python數據結構在算法上找到這種格式的“唯一對”?

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

[2, 2, 3]

這是不可能的,因為有兩個2。

但是,可能會有一個列表列表:

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。 給定一個列表中的多個列表,如何“更新”字典?

這是一個算法問題,我不知道最有效的解決方案。 我的想法是以某種方式將值緩存在列表中並枚舉對……但這太慢了。 我猜itertools有一些有用的東西。

您想要的是對列表中組合產生的對進行計數。 您可以找到帶有Countercombinations

from itertools import combinations
from collections import Counter

list2 = [2, 3, 4]

count = Counter(combinations(list2, 2))

print(count)

輸出量

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

至於您的清單清單,我們會使用每個子清單的結果來更新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)

輸出量

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

我的方法遍歷輸入dict (線性復雜度),並將每個鍵與它的第一個可用整數配對(此復雜度取決於您問題的確切規格-例如,每個列表是否可以包含無限的子列表?),然后將它們插入到輸出中dict(恆定復雜度)。

import os 
import sys 


def update_results(result_map, tup):
    # Update dict inplace
    # Don't need to keep count here
    try:
        result_map[tup] += 1
    except KeyError:
        result_map[tup] = 1
    return


def algo(input):
    # Use dict to keep count of unique pairs while iterating
    # over each (key, v[i]) pair where v[i] is an integer in 
    # list input[key]
    result_map = dict()
    for key, val in input.items():
        key_pairs = list()
        if isinstance(val, list):
            for x in val:
                if isinstance(x, list):
                    for y in x:
                        update_results(result_map, (key, y))
                else:
                    update_results(result_map, (key, x))
        else:
            update_results(result_map, (key, val))
    return len(result_map.keys())


>>> input = { 1: [1, 2], 2: [1, 2, [2, 3]] }
>>> algo(input)
>>> 5

我敢肯定,還有一種更精致的方法可以做到這一點(再次,這取決於您所問問題的具體規格),但這可以使您入門(無需導入)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM