简体   繁体   English

Python中Dictionary中元素的组合

[英]Combinations of elements in Dictionary in Python

Okay so I've a Dictionary in Python like this: 好的,所以我在Python中使用这样的字典:

dict={'a':'','b':'2','c':'3'}

How do you get an output like this: 你如何获得这样的输出:

[['a','b','c'],
['a','2','c'],
['a','b','3'],
['a','2','3']]

In this result, the original position of the elements don't change but they are simply replaced by their respective meanings in the dictionary. 在这个结果中,元素的原始位置不会改变,但它们只是被字典中各自的含义所取代。 We get a list of lists with different combinations of the elements. 我们得到一个列表,列表中包含不同的元素组合。

Is this possible? 这可能吗? How do I do this? 我该怎么做呢? Please help. 请帮忙。

Dictionaries aren't ordered, so there is no "original position of the elements". 字典不是有序的,所以没有“元素的原始位置”。 That said, I think you can use itertools.product to generate all the possibilities: 也就是说,我认为您可以使用itertools.product来生成所有可能性:

>>> from itertools import product
>>> d = {'a':'','b':'2','c':'3'}
>>> poss = [(k,v) if v else (k,) for k,v in d.items()]
>>> list(product(*poss))
[('a', 'c', 'b'), ('a', 'c', '2'), ('a', '3', 'b'), ('a', '3', '2')]

where poss describes all the choices you want to choose between for each term: 其中poss描述了所有你想为每学期之间进行选择的选择:

>>> poss
[('a',), ('c', '3'), ('b', '2')]

You could sort by the order of the keys, I guess: 您可以按键的顺序排序,我想:

>>> poss = [(k,v) if v else (k,) for k,v in sorted(d.items())]
>>> list(product(*poss))
[('a', 'b', 'c'), ('a', 'b', '3'), ('a', '2', 'c'), ('a', '2', '3')]

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

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