简体   繁体   English

Python 词典 如何创建列表项的组合?

[英]Python Dictionary How to create combinations of list items?

I have a dictionary which has value as a list.我有一本具有列表价值的字典。

thisdict = {  'G1' : [10,20],
              'G2' : [12,13]

}

I want to create new dictionary with all possible 4 combinations.我想用所有可能的 4 种组合创建新字典。

C1:[10,12] C1:[10,12]

C2:[10,13] C2:[10,13]

C3:[20,12] C3:[20,12]

C4:[20,13] C4:[20,13]

How do I create that?我该如何创建它?

I think you are looking for: itertools.combinations()我认为您正在寻找:itertools.combinations()

This might help too Getting all combinations of key/value pairs in Python dict这也可能有帮助Getting all combinations of key/value pairs in Python dict

Is this acceptable?这是可以接受的吗?

from itertools import product

d = {}
offset = 1
for e in product(thisdict['G1'], thisdict['G2']):
    d[f'C{offset}'] = list(e)
    offset += 1
print(d)

Output: Output:

{'C1': [10, 12], 'C2': [10, 13], 'C3': [20, 12], 'C4': [20, 13]}

As other stated, you can use itertools.product for this.如其他所述,您可以为此使用itertools.product

But you have just two lists, you can also just use two for loops:但是你只有两个列表,你也可以只使用两个for循环:

> d = { f'C{i+1}': {'G1':g1e, 'G2':g2e}
      for i, (g1e, g2e) in
      enumerate((g1e, g2e) for g1e in thisdict['G1']
                           for g2e in thisdict['G2']) }
> d
{'C1': {'G1': 10, 'G2': 12},
 'C2': {'G1': 10, 'G2': 13},
 'C3': {'G1': 20, 'G2': 12},
 'C4': {'G1': 20, 'G2': 13}}

NB: I used the format requested in the comment to another answer.注意:我使用了另一个答案的评论中要求的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM