簡體   English   中英

python中集合的字典元素

[英]Elements of dict of sets in python

我有一本這樣的字典:

dict1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}

從這個字典中,我想建立另一個字典,該字典計算dict1中每個其他值中鍵的出現次數,即結果應該是:

result_dict = {0: 1, 1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1}

我的代碼是這樣的:

dict1 =  {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5:set([2]), 6: set([])}
result_dict = {}
for pair in dict1.keys():
    temp_dict = list(dict1.keys())

    del temp_dict[pair]
    count = 0
    for other_pairs in temp_dict :
        if pair in dict1[other_pairs]:
            count = count + 1
    result_dict[pair] = count  

此代碼的問題在於,處理大量數據時,它的運行速度非常慢。 另一嘗試是在一行中,如下所示:

result_dict = dict((key ,dict1.values().count(key)) for key in dict1.keys())  

但這會給我錯誤的結果,因為dict1的值已設置:

{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}

提前非常感謝

我想,對於第一個步驟,我想知道那里有哪些值:

all_values = set().union(*dict1.values())

然后,我嘗試計算每個值出現了多少次:

result_dict = {}
for v in all_values:
    result_dict[v] = sum(v in dict1[key] for key in dict1)

另一種方法是使用collections.Counter

result_dict = Counter(v for set_ in dict1.values() for v in set_)

這可能比我的第一個解決方案“更干凈”-但這確實涉及嵌套的理解,這可能有點難以理解。 它確實可以工作:

>>> from collections import Counter
>>> dict1
{0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
>>> result_dict = Counter(v for set_ in dict1.values() for v in set_)

只需使用dict1的鍵創建第二個字典,值從0開始。 然后遍歷dict1集合中的值,並隨着dict1增加而遞增result_dict值。 運行時為O(n) ,其中ndict1組中值的dict1

dict1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5:set([2]), 6: set([])}
result_dict = dict.fromkeys(dict1.keys(), 0)
# {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}

for i in dict1.keys():
    for j in dict1[i]: 
        result_dict[j] += 1

print result_dict
# {0: 1, 1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1}

暫無
暫無

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

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