【问题标题】:Combine two lists l1 x l2 into tuples [duplicate]将两个列表l1 x l2组合成元组[重复]
【发布时间】:2021-07-27 01:40:37
【问题描述】:

如何在一行中生成一个包含所有 l1 x l2 对的元组的列表。

示例: [1,2] et ['a','b'] -> [(1,'a'), (1,'b'), (2,'a'), (2,'b')]

我尝试使用 map() 和 zip() 但我还没有找到答案。

【问题讨论】:

  • 您想要列表中的产品

标签: python list


【解决方案1】:

你可以使用itertools.product

from itertools import product
numbers = [1,2]
letters = ['a','b']
result = list(product(numbers,letters))

【讨论】:

    【解决方案2】:

    就这么简单。 下面是 listcomprehension 中的双重迭代示例。

    numbers = [1,2]
    letters = ['a','b']
    new  = [(num,letter) for num in numbers for letter in letters]
    

    输出

    [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
    

    【讨论】:

      【解决方案3】:

      您可以使用列表推导。

      list3 = [(l1,l2) for l1 in list1 for l2 in list2]
      

      【讨论】:

        猜你喜欢
        • 2015-10-30
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 2018-08-12
        • 2013-01-31
        • 2018-10-05
        • 1970-01-01
        相关资源
        最近更新 更多