【问题标题】:What is a Pythonic way to get a list of tuples of all the possible combinations of the elements of two lists?获取两个列表元素所有可能组合的元组列表的 Pythonic 方法是什么?
【发布时间】:2011-01-28 02:50:00
【问题描述】:

假设我有两个不同大小的列表

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

a 的一个元素和b 的一个元素的所有可能组合中获取元组c 的列表的Pythonic 方法是什么?

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

c 中元素的顺序无关紧要。

具有两个for 循环的解决方案是微不足道的,但它似乎不是特别Pythonic。

【问题讨论】:

标签: list python


【解决方案1】:

使用列表推导:

>>> 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')]

【讨论】:

    【解决方案2】:

    试试itertools.product

    【讨论】:

    • 谢谢。这和@Moe 的答案似乎同样有效,所以我任意决定接受这个,因为生成器在我的代码中的这个特定点更有用。两者都 +1。
    • 在编写任何代码之前,我总是会查看 Python 标准库,例如 operator、itertools、functools 和 collections。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2010-10-02
    • 2023-02-14
    • 2015-11-12
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多