简体   繁体   中英

Combiing two python lists into a cartesian product

I have two lists in python that have unique values in them like so:

# 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:

# 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() . 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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