簡體   English   中英

遍歷 collections.defaultdict(list)

[英]Iterating over collections.defaultdict(list)

import itertools
import collections

def get_pairs(some_list, limit):
    min = 2
    pair_dict = collections.defaultdict(list)

    for x in range(min, limit+1):
        pair_dict[x].append(list(itertools.combinations(some_list, x)))

    return pair_dict

z = get_pairs([1, 2, 3, 4], 4)
for key, value in z.items():
    print("Key: {}", "Value: {}".format(key, value))

Output:
Key: {} Value: 2
Key: {} Value: 3
Key: {} Value: 4

我期待 key 以 2、3、4 的形式出現,而 value 成為一個列表。 像下面的東西

{
 2: [[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]], 
 3: [[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]], 
 4: [[(1, 2, 3, 4)]]
}

我的代碼有什么問題,或者我在這里遺漏了什么?

您的print聲明只是搞砸了。 將其更改為:

print("Key: {}, Value: {}".format(key, value))

你的原創

print("Key: {}", "Value: {}".format(key, value))

正在打印文字字符串"Key: {}" (沒有任何格式),然后是格式化的字符串"Value: {}".format(key, value) ,它使用第一個參數key來填充其唯一的占位符。

占位符"{}"看起來像一個空dict和所有 =) 在這里很容易被愚弄

暫無
暫無

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

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