Python permutation

How to do the following in python:

first = ['John', 'David', 'Sarah']
last = ['Smith', 'Jones']

combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones']

Is there a way to combine all permutations?

+3
source share
4 answers

itertools.product

import itertools
combined = [f + ' ' + l for f, l in itertools.product(first, last)]
+11
source

Not sure if there is a more elegant solution, but this should work:

[x + " " + y for x in first for y in last]

+7
source

product itertools .

product(first, last)

first last. , , . :

combined = [" ".join(pair) for pair in product(first, last)]

:

combined = [pair[0] + " " + pair[1] for pair in product(first, last)]

, . "".join(), C.

+4

- python , :

def permutations(first, second):
  result = []
  for i in range(len(first)):
    for j in range(len(second)):
      result.append(first[i] + ' ' + second[j])
  return result 
0
source

All Articles