[英]Combiing two python lists into a cartesian product
I have two lists in python that have unique values in them like so:我在 python 中有两个列表,它们具有独特的值,如下所示:
# Sepearate lists
first_list = ["Hello", "World"]
second_list = ["A", "B", "C"]
I want the first_list to actually become a cartesian product of the two separate lists:我希望 first_list 实际上成为两个单独列表的笛卡尔积:
# So first_list should be
first_list = ["A:Hello", "B:Hello", "C:Hello", "A:World", "B:World", "C:World"]
I know I can do it like this (psuedo-code) but there should be a faster more precise way I think:我知道我可以这样做(伪代码),但我认为应该有一种更快更精确的方法:
#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
The psuedo code is what I want but is there a better way?伪代码是我想要的,但有更好的方法吗?
Your way is fine, but you can also use itertools.product()
.你的方法很好,但你也可以使用
itertools.product()
。 For example like so例如像这样
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)])
It will print the following它将打印以下内容
['A:Hello', 'B:Hello', 'C:Hello', 'A:World', 'B:World', 'C:World']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.