【问题标题】:Python: How to concatenate all possible combinations in two lists? [duplicate]Python:如何连接两个列表中的所有可能组合? [复制]
【发布时间】:2019-11-29 07:20:30
【问题描述】:
list1=['A','B']

list2=[1,2,3]

如何使输出按此顺序显示所有可能的组合并且不带任何括号?

A1

A2

A3

B1

B2

B3

【问题讨论】:

    标签: python concatenation


    【解决方案1】:

    你可以使用itertools.product:

    from itertools import product
    list1 = ['A', 'B']
    list2 = [1, 2, 3]
    for e1,e2 in product(list1, list2):
        print(e1+str(e2))
    

    输出:

    A1
    A2
    A3
    B1
    B2
    B3
    

    【讨论】:

      【解决方案2】:

      你可以使用:

      list3 = [a+b for a in list1 for b in map(str, list2)]
      print(*list3, sep = "\n") 
      A1
      A2
      A3
      B1
      B2
      B3
      

      【讨论】:

        【解决方案3】:

        你可以使用:

        list1 = ['A', 'B']
        list2 = [1, 2, 3]
        for i in list1:
            for j in list2:
                print(i+str(j))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-12
          • 2022-09-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多