如何找到 python 中字符串向量之间的所有组合

How to find all combinations between string vectors in python

考虑以下两个字符串序列:

Salutation = ["Hello", "Hi"]
Names = ["Alice", "Matt", "Franck", "Julia"]

我正在寻找将这些序列合并到

中的干净方法
["Hello_Alice", "Hi_Alice", "Hello_Matt", "Hi_Matt", "Hello_Franck", "Hi_Franck", "Hello_Julia", "Hi_Julia"]

或使用任何分隔符。

R 中的等价物是:

c(outer(Salutations, Names, paste, sep="_"))

一种方法是像这样使用嵌套 for 循环:

l = []
for s in Salutation:
    for n in Names:
        l.append(s + "_" + n)

itertools.product 就是您要找的

import itertools
output = ['_'.join(i) for i in itertools.product(Salutation, Names)]
#or whatever separator you want