如何从python中的二维列表中获取所有可能的项目组合? [英] how to get all possible combination of items from 2-dimensional list in python?
本文介绍了如何从python中的二维列表中获取所有可能的项目组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有找到更好的方法在标题中表达这个问题.如果可以,请进行编辑.
I didn't find a better way to phrase this question in the title. If you can, please edit.
我有一个这样的列表列表:
I have a list of lists like this:
a = [['a','b'],[1,2]]
现在,我想要一个可以吐出所有可能组合的函数,如下所示:
now, I'd like a function that spits out all possible combination like this:
[['a',1],['a',2],['b',1],['b',2]]
其中a中的列表数量事先未知,每个子列表的长度也不事先知道,但是出现的所有组合都应包含每个子列表中的一项.
where nor the number of lists in a is known in advance, nor is the length of each of the sub lists known in advance, but all the combinations that come out should contain 1 item from every sublist.
推荐答案
您需要 itertools.product()
:
You need itertools.product()
:
>>> list(itertools.product(*a))
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
这篇关于如何从python中的二维列表中获取所有可能的项目组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文