【问题标题】:Cartesian product of two lists in python letters and numbers [duplicate]python字母和数字中两个列表的笛卡尔积[重复]
【发布时间】:2019-10-10 10:11:27
【问题描述】:

当前

list1 = ['A','B','C']
list2 = [1,2,3]

想要的

list 3 = [['A', 1], ['A', 2], ['A', 3], ['B', 1], ['B', 2],['B', 3],
 ['C', 1], ['C', 2], ['C', 3]]

我尝试过的

list3 = [l+str(n) for l in list1 for n in list2]

结果:

['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']

【问题讨论】:

  • 为什么不直接使用itertools.product
  • list3 = [[l,str(n)] for l in list1 for n in list2] 注意第一部分的括号

标签: python pandas list loops


【解决方案1】:

你很亲密:

[[l,n] for l in list1 for n in list2]

【讨论】:

    【解决方案2】:
    [[l]+[n] for l in list1 for n in list2]
    

    【讨论】:

      【解决方案3】:

      正如 Mark 已经提到的,itertools.product 将是要走的路。但是如果你想继续使用列表推导,正确的行应该是

      list3 = [ [l, str(n)] for l in list1 for n in list2 ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2012-01-03
        • 2021-01-25
        • 2012-02-24
        • 2011-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多