C. Cooney
C. Cooney

Reputation: 591

Fastest way to combine two lists into a single combined element featuring all combinations?

I have two lists:

fname
Mike
Dave
Sarah

sname
Smith
Thomas
Hamilton

I'd like to create a combined list with all possible elements with a special separator in the middle:

Mike_v_Smith
Mike_v_Thomas
Mike_v_Hamilton
Dave_v_Smith
... (etc)

I can manage the outer join, but how would I embed the 'v' in the middle in an elegant way?

Upvotes: 0

Views: 209

Answers (6)

Mathieu Rene
Mathieu Rene

Reputation: 994

The itertools package has a product function which will return all permutations of a series of iterables.

import itertools
fname = ['Mike', 'Dave', 'Sarah']
sname = ['Smith', 'Thomas', 'Hamilton']
[f'{f}_v_{s}' for f, s in itertools.product(fname, sname)]

Resulting in:

['Mike_v_Smith',
 'Mike_v_Thomas',
 'Mike_v_Hamilton',
 'Dave_v_Smith',
 'Dave_v_Thomas',
 'Dave_v_Hamilton',
 'Sarah_v_Smith',
 'Sarah_v_Thomas',
 'Sarah_v_Hamilton']

Upvotes: 2

user10873315
user10873315

Reputation:

result = [f"{f}_v_{l}" for f in "Mike,Dave,Sarah".split(",") for l in "Smith,Thomas,Hamilton".split(",")]

Upvotes: 1

Andy Pavlov
Andy Pavlov

Reputation: 316

Make two loops over first and second lists and combine iterated items to formatted string.

fname = ['Mike', 'Dave', 'Sarah',]
sname = ['Smith', 'Thomas', 'Hamilton',]

list_ns = ['{}_v_{}'.format(n, s) for n in fname for s in sname]

# ['Mike_v_Smith', 'Mike_v_Thomas', 'Mike_v_Hamilton', 'Dave_v_Smith', 'Dave_v_Thomas', 'Dave_v_Hamilton', 'Sarah_v_Smith', 'Sarah_v_Thomas', 'Sarah_v_Hamilton']

Upvotes: 0

user16329476
user16329476

Reputation:

I'd just join the two elements from each tuple in the result of itertools.product, using the string "_v_":

from itertools import product


fname = ["Mike", "Dave", "Sarah"]
sname = ["Smith", "Thomas", "Hamilton"]

names = ["{}_v_{}".format(combo[0], combo[1]) for combo in product(fname, sname)]
print(names)

Upvotes: 0

Max Shouman
Max Shouman

Reputation: 1331

str.join() allows you to choose any separator for your list elements.

Since you asked for an elegant way, here's a list comprehension that does for the purpose:

merged_list = ["_v_".join((k, v)) for k, v in zip(list_1, list_2)]

of course, assuming that your lists are of the same length

Upvotes: 0

Hammurabi
Hammurabi

Reputation: 1179

You can iterate through both lists, and add 'v' between as you go:

list1 = ['Mike', 'Dave']
list2 = ['Smith', 'Thomas']

output = []
for name1 in list1:
    for name2 in list2:
        output.append(name1 + '_v_' + name2)

print(output)
# ['Mike_v_Smith', 'Mike_v_Thomas', 'Dave_v_Smith', 'Dave_v_Thomas']

Upvotes: 0

Related Questions