-2

There are 2 lists (but there can be many):

a = ['Sasha ','walked along ','the highway']
b = ['Masha ','ran on ','the road']

I need to display all options:

Sasha walked along the highway
Sasha walked along the road
Masha walked along the highway
Masha walked along the road
Sasha ran on the highway
Sasha ran on the road
Masha ran on the highway
Masha ran on the road

jpp
  • 159,742
  • 34
  • 281
  • 339
Wood
  • 27
  • 7
  • Please read [ask] and [mcve]. – Nic3500 Nov 23 '18 at 18:47
  • Possible duplicate of [How to extract the n-th elements from a list of tuples in python?](https://stackoverflow.com/questions/3308102/how-to-extract-the-n-th-elements-from-a-list-of-tuples-in-python) – Alex Nov 23 '18 at 18:48

4 Answers4

1

Using itertools.product with str.join:

from itertools import product

a = ['Sasha ','walked along ','the highway']
b = ['Masha ','ran on ','the road']

# option 1: list comprehension
res = [''.join(tup) for tup in product(*zip(a, b))]

# option 2: map
res = list(map(''.join, product(*zip(a, b))))

['Sasha walked along the highway',
 'Sasha walked along the road',
 'Sasha ran on the highway',
 'Sasha ran on the road',
 'Masha walked along the highway',
 'Masha walked along the road',
 'Masha ran on the highway',
 'Masha ran on the road']
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Since you want all the options to be printed, you can try this:

a = ['Sasha ','walked along ','the highway']
b = ['Masha ','ran on ','the road']
ab = [list(i) for i in zip(a,b)]
for i in ab[0]:
    for j in ab[1]:
        for k in ab[2]:
            print(i,j,k)

output:

Sasha  walked along  the highway
Sasha  walked along  the road
Sasha  ran on  the highway
Sasha  ran on  the road
Masha  walked along  the highway
Masha  walked along  the road
Masha  ran on  the highway
Masha  ran on  the road
Sandesh34
  • 279
  • 1
  • 2
  • 14
0

Simply, without itertools and zip:

def scr(*lists):

    rslt=[""]
    for idx in range(len(lists[0])): # all of the lists has the same length

        r=[]
        for s in rslt:
            for l in lists:
                r.append( s+l[idx] )              
        rslt=r
    return rslt


print(scr(a,b))
kantal
  • 2,331
  • 2
  • 8
  • 15
0

Redid your version. Here's the right solution:

    a = ['Sasha ','Masha ']
    b = ['walked along ','ran on ']
    c = ['the highway','the road']

    ab = [list(i) for i in (a,b,c)]
    for x in ab[0]:
        for y in ab[1]:
            for z in ab[2]:
                print(x + y + z)

    Sasha walked along the highway
    Sasha walked along the road
    Sasha ran on the highway
    Sasha ran on the road
    Masha walked along the highway
    Masha walked along the road
    Masha ran on the highway
    Masha ran on the road
Wood
  • 27
  • 7