How to generate each possible combination of members from two lists (in Python)

StackOverflow https://stackoverflow.com/questions/23578518

  •  19-07-2023
  •  | 
  •  

Domanda

I am a Python newbie and I've been trying to find the way to generate each possible combination of members from two lists:

left = ['a', 'b', 'c', 'd', 'e'] right = ['f', 'g', 'h', 'i', 'j']

The resulting list should be something like:

af ag ah ai aj bf bg bh bi bj cf cg ch ci cj etc...

I made several experiments with loops but I can't get it right: The zip function but it wasn't useful since it just pairs 1 to 1 members: for x in zip(left,right): print x and looping one list for the other just returns the members of one list repeated as many times as the number of members of the second list :(

Any help will be appreciated. Thanks in advance.

È stato utile?

Soluzione

You can use for example list comprehension:

left = ['a', 'b', 'c', 'd', 'e']
right = ['f', 'g', 'h', 'i', 'j']
result = [lc + rc for lc in left for rc in right]
print result

The result will look like:

['af', 'ag', 'ah', 'ai', 'aj', 'bf', 'bg', 'bh', 'bi', 'bj', 'cf', 'cg', 'ch', 'ci', 'cj', 'df', 'dg', 'dh', 'di', 'dj', 'ef', 'eg', 'eh', 'ei', 'ej']
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top