簡體   English   中英

如何遍歷列表字典並將每個迭代與所有鍵中的項目配對?

[英]How do I iterate through a dictionary of lists and pair each iteration with an item from all the keys?

我需要遍歷列表字典,不知道字典將有多少列表,但仍然將每個列表值與字典中另一個鍵生成的任何其他列表值配對(如果存在另一個鍵)。 我有以下代碼:

def loop_rec(codes, currentcode={}):
    if len(codes.keys())>1:
        for key in sorted(codes):
            codespop = dict(codes)
            loop = codespop.pop(key)
            for x in loop:
                currentcode[key]=x
                loop_rec(codespop,currentcode)
            break
    else:
        for key in codes.keys():
            loop = codes[key]
            for x in loop:
                currentcode[key]=x
                print currentcode

所以,如果我有以下字典:

codes = {"coarse":range(4),"fine":range(2)}

我得到這個結果:

>>> loop_rec(codes)
{'fine': 0, 'coarse': 0}
{'fine': 1, 'coarse': 0}
{'fine': 0, 'coarse': 1}
{'fine': 1, 'coarse': 1}
{'fine': 0, 'coarse': 2}
{'fine': 1, 'coarse': 2}
{'fine': 0, 'coarse': 3}
{'fine': 1, 'coarse': 3}

這是一種蠻力方法,並希望采用更“Pythonic”的方式。 我搜索了大量相當的東西,但是大多數方法都沒有導致粗略和精細值一起用於每次迭代。 也希望它首先循環粗略,但排序的命令不起作用。

編輯:剛剛意識到排序的命令正在工作,打印輸出只是沒有排序。 我不在乎是否按順序打印。

如果我正確理解你的問題,你想要把所有列表中的笛卡爾積作為dict的值。 您可以使用itertools.product來完成此任務。

import itertools
def dict_product(d):
    list_of_dicts = []
    for values in itertools.product(*d.values()):
        item = dict(zip(d.keys(),values))
        list_of_dicts.append(item)
    return list_of_dicts


codes = {"coarse":range(4),"fine":range(2),"zesty":range(3)}
for item in dict_product(codes):
    print(item)

結果:

{'zesty': 0, 'fine': 0, 'coarse': 0}
{'zesty': 0, 'fine': 0, 'coarse': 1}
{'zesty': 0, 'fine': 0, 'coarse': 2}
{'zesty': 0, 'fine': 0, 'coarse': 3}
{'zesty': 0, 'fine': 1, 'coarse': 0}
{'zesty': 0, 'fine': 1, 'coarse': 1}
{'zesty': 0, 'fine': 1, 'coarse': 2}
{'zesty': 0, 'fine': 1, 'coarse': 3}
{'zesty': 1, 'fine': 0, 'coarse': 0}
{'zesty': 1, 'fine': 0, 'coarse': 1}
{'zesty': 1, 'fine': 0, 'coarse': 2}
{'zesty': 1, 'fine': 0, 'coarse': 3}
{'zesty': 1, 'fine': 1, 'coarse': 0}
{'zesty': 1, 'fine': 1, 'coarse': 1}
{'zesty': 1, 'fine': 1, 'coarse': 2}
{'zesty': 1, 'fine': 1, 'coarse': 3}
{'zesty': 2, 'fine': 0, 'coarse': 0}
{'zesty': 2, 'fine': 0, 'coarse': 1}
{'zesty': 2, 'fine': 0, 'coarse': 2}
{'zesty': 2, 'fine': 0, 'coarse': 3}
{'zesty': 2, 'fine': 1, 'coarse': 0}
{'zesty': 2, 'fine': 1, 'coarse': 1}
{'zesty': 2, 'fine': 1, 'coarse': 2}
{'zesty': 2, 'fine': 1, 'coarse': 3}

在此示例中,迭代順序是粗略精細的,但不保證此行為。 在CPython 3.6及更高版本中,字典是有序的,但這是一個實現細節,將來可能會發生變化。

暫無
暫無

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

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