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

时间:2015-07-05 19:36:47

标签: python string character sequence outer-join

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

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="_"))

2 个答案:

答案 0 :(得分:9)

itertools.product是您正在寻找的

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

答案 1 :(得分:1)

一种方法是使用嵌套的for循环:

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