【问题标题】:Python - Create multiple lists from elementwise concatenation of two listsPython - 从两个列表的元素连接创建多个列表
【发布时间】:2026-02-10 15:50:01
【问题描述】:
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']

def comb(lst1, lst2):
    for i in lst1:
            new_list = []
            for j in lst2:
                new_list.append(i + '_' + j)
    return new_list
print(comb(lst1, lst2)) 

给我:

['c_1', 'c_2']

我希望得到:

['a_1', 'a_2']

['b_1', 'b_2']

['c_1', 'c_2']

有人可以指出我的代码中的错误吗?谢谢!

【问题讨论】:

  • new_list 定义移到第一个 for 循环之外。
  • @PéterLeéh 那行不通。它只会创建一个包含所有元素的列表。不像 OP 所期望的那样。
  • 很可能是这个的一个特例:*.com/questions/12935194/…

标签: python


【解决方案1】:

试试这个

res = [[f'{x}_{y}' for y in lst2] for x in lst1]
print(res)

输出:

[['a_1', 'a_2'], ['b_1', 'b_2'], ['c_1', 'c_2']]

【讨论】:

    【解决方案2】:

    试试这个:

    lst1 = ['a', 'b', 'c']
    lst2 = ['1', '2']
    
    def comb(lst1, lst2):
        finalList = []
        for i in lst1:
                new_list = []
                for j in lst2:
                    new_list.append(i + '_' + j)
                finalList.append(new_list)
        return finalList
        
    print(comb(lst1, lst2)) 
    

    new_list 每次执行第一个 for 循环时都会为空。因此,创建另一个列表以在其被覆盖之前存储该值,并返回包含 new_list 的所有值的第二个列表。

    【讨论】:

    • 更好的方法是使用列表理解。请参阅 deadshot 的answer
    【解决方案3】:

    看看 new_list = [] 在哪里。您在每次循环迭代中从头开始创建它。把它移到前面就行了。

    如果您只想查看打印的 3 个元素,请将 return 更改为 print。

    lst1 = ['a', 'b', 'c']
    lst2 = ['1', '2']
    
    def comb(lst1, lst2):
        for i in lst1:
            new_list = []
            for j in lst2:
                new_list.append(i + '_' + j)
            print(new_list)
    comb(lst1, lst2)
    

    【讨论】:

    • 如果将 print 替换为 return ,则只会得到第一个结果。您需要将每个构造的列表添加到另一个列表中,然后返回 - 请参阅*.com/a/63591903/7505395
    • 最好的解决方案是由 deadshot *.com/a/63591907/10815718 编写的解决方案。使用 print 的解决方案只是 States.the.Obvious 想要作为输出的直接解决方案,
    【解决方案4】:

    试试这个;

    lst1 = ['a', 'b', 'c']
    lst2 = ['1', '2']
    new_list = []
    for i in lst1:
        l1=[]
        for j in lst2:
            l1.append(i + '_' + j)
        new_list.append(l1)
    print(new_list)
    

    【讨论】:

      【解决方案5】:
      lst1 = ['a', 'b', 'c']
      lst2 = ['1', '2']
      for e1 in lst1:
          newList = []
          for e2 in lst2:
              newList.append(e1 + "_" + e2)
          print(newList)
      
      
      Output:
      ['a_1', 'a_2']
      ['b_1', 'b_2']
      ['c_1', 'c_2']
      

      【讨论】: