简体   繁体   English

什么是Pythonic方法来获取两个列表元素的所有可能组合的元组列表?

[英]What is a Pythonic way to get a list of tuples of all the possible combinations of the elements of two lists?

Suppose I have two differently-sized lists 假设我有两个不同大小的列表

a = [1, 2, 3]
b = ['a', 'b']

What is a Pythonic way to get a list of tuples c of all the possible combinations of one element from a and one element from b ? 什么是Python化的方式来获得一个元组列表c从一个元素的所有可能组合的a从一个元素和b

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

The order of elements in c does not matter. c中元素的顺序无关紧要。

The solution with two for loops is trivial, but it doesn't seem particularly Pythonic. 具有两个for循环的解决方案是微不足道的,但它似乎并不特别是Pythonic。

Use a list comprehension: 使用列表理解:

>>> 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.

相关问题 Pythonic将两个列表“合并”到元组列表的方法 - Pythonic way to “merge” two lists to a list of tuples 如何将一个列表分成两个列表并获得所有可能的组合 - how to divide a list to two lists and get all possible combinations 元组列表的所有可能组合 - All possible combinations of a list of tuples 合并2个元组列表并在元组中添加非唯一值的Pythonic方法是什么? - What is the Pythonic way to merge 2 lists of tuples and add the nonunique values in the tuples? 如何从 python 元组列表中获取所有可能的组合 - How to get all possible combinations from python list of tuples 列出列表列表的所有组合,其中两个元素都不相同 - List all combinations of a list of lists where no two elements are the same Lisp:如何从列表中包含的列表中获取所有可能的元素组合? - Lisp: How to get all possible combinations of the elements from lists contained on a list? 如何获得两个不同列表的所有可能组合? - How to get all possible combinations of two different lists? 什么是确保列表中所有元素不同的最pythonic方法? - What's the most pythonic way to ensure that all elements of a list are different? 获取两个列表之间所有可能的组合,包括多个连接 - Get all possible combinations between two lists, including multiple connections
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM