How to find all combinations between string vectors in python
本问题已经有最佳答案,请猛点这里访问。
考虑以下两个字符串序列:
1 2 | Salutation = ["Hello","Hi"] Names = ["Alice","Matt","Franck","Julia"] |
我正在寻找把这些序列合并到
1 | ["Hello_Alice","Hi_Alice","Hello_Matt","Hi_Matt","Hello_Franck","Hi_Franck","Hello_Julia","Hi_Julia"] |
号
或者用任何分隔符。
R中的等效值为:
1 | c(outer(Salutations, Names, paste, sep="_")) |
你要找的是
1 2 3 | import itertools output = ['_'.join(i) for i in itertools.product(Salutation, Names)] #or whatever separator you want |
号
一种方法是使用嵌套的for循环,如下所示:
1 2 3 4 | l = [] for s in Salutation: for n in Names: l.append(s +"_" + n) |