繁体   English   中英

将两个 python 列表组合成笛卡尔积

[英]Combiing two python lists into a cartesian product

我在 python 中有两个列表,它们具有独特的值,如下所示:

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

我希望 first_list 实际上成为两个单独列表的笛卡尔积:

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

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

#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

伪代码是我想要的,但有更好的方法吗?

你的方法很好,但你也可以使用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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM