代码之家  ›  专栏  ›  技术社区  ›  cdub

将两个python列表合并为笛卡尔乘积

  •  0
  • cdub  · 技术社区  · 3 年前

    我在python中有两个列表,其中有唯一的值,如下所示:

    # Sepearate lists
    first_list = ["Hello", "World"]
    second_list = ["A", "B", "C"]
    

    # So first_list should be
    first_list = ["A:Hello", "B:Hello", "C:Hello", "A:World", "B:World", "C:World"]
    

    我知道我可以这样做(psuedo代码),但我认为应该有一种更快更精确的方式:

    #Temp list
    temp_list = []
    
    for s in second_list: 
        for f in first_list:
            # The append expression is more C# than python and need that fixed
            temp_list.append(s + ":" f)
    
    first_list = temp_list
    

    2 回复  |  直到 3 年前
        1
  •  2
  •   vidstige Joe Kington    3 年前

    itertools.product() . 比如说

    import itertools
    # Sepearate lists
    first_list = ["Hello", "World"]
    second_list = ["A", "B", "C"]
    
    print([f'{b}:{a}' for a, b in itertools.product(first_list, second_list)])
    

    它将打印以下内容

    ['A:Hello', 'B:Hello', 'C:Hello', 'A:World', 'B:World', 'C:World']
    
        2
  •  1
  •   j1-lee    3 年前

    使用f-string进行列表理解可能更简洁易读。

    first_list = ["Hello", "World"]
    second_list = ["A", "B", "C"]
    
    first_list = [f'{y}:{x}' for x in first_list for y in second_list]
    print(first_list) # ['A:Hello', 'B:Hello', 'C:Hello', 'A:World', 'B:World', 'C:World']