2

Consider the two following string sequences:

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

I am looking for clean way to merge those sequences into

["Hello_Alice", "Hi_Alice", "Hello_Matt", "Hi_Matt", "Hello_Franck", "Hi_Franck", "Hello_Julia", "Hi_Julia"]

or with whatever separator.

The equivalent in R would be:

c(outer(Salutations, Names, paste, sep="_"))
Remi.b
  • 17,389
  • 28
  • 87
  • 168

2 Answers2

9

itertools.product is what you're looking for

import itertools
output = ['_'.join(i) for i in itertools.product(Salutation, Names)]
#or whatever separator you want
NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
1

One way would be to use nested for loops like this:

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