簡體   English   中英

2個列表中所有可能的字典組合排列

[英]All possible permutations of dictionaries combinations out of 2 lists

假設我在python中有2個列表:

keys = [1, 2, 3, 4, 5, 6]

values = [7, 8, 9]

我希望從這兩個列表中獲得所有排列

就像是:

d = [{1:7, 2:8, 3:9}, {1:8, 2:9, 3:7}, ....... ]

我怎么能實現這一目標?

你的意思是這樣的嗎?

>>> import itertools
>>> keys = [1, 2, 3, 4, 5, 6]
>>> values = [7, 8, 9]
>>> d = [dict(zip(kperm, values)) for kperm in itertools.permutations(keys, len(values))]
>>> len(d)
120
>>> d[:10]
[{1: 7, 2: 8, 3: 9}, {1: 7, 2: 8, 4: 9}, {1: 7, 2: 8, 5: 9}, {1: 7, 2: 8, 6: 9}, {1: 7, 2: 9, 3: 8}, {1: 7, 3: 8, 4: 9}, {1: 7, 3: 8, 5: 9}, {1: 7, 3: 8, 6: 9}, {1: 7, 2: 9, 4: 8}, {1: 7, 3: 9, 4: 8}]
>>>import itertools
>>>list(itertools.product(*[[1, 2, 3, 4, 5, 6],[7, 8, 9]]))
>>>[(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9), (4, 7), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9), (6, 7), (6, 8), (6, 9)]

暫無
暫無

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

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