[英]What is a Pythonic way to get a list of tuples of all the possible combinations of the elements of two lists?
假设我有两个不同大小的列表
a = [1, 2, 3]
b = ['a', 'b']
什么是Python化的方式来获得一个元组列表c
从一个元素的所有可能组合的a
从一个元素和b
?
>>> print c
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
c
中元素的顺序无关紧要。
具有两个for
循环的解决方案是微不足道的,但它似乎并不特别是Pythonic。
使用列表理解:
>>> a = [1, 2, 3]
>>> b = ['a', 'b']
>>> c = [(x,y) for x in a for y in b]
>>> print c
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
试试itertools.product
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.