How to join strings from a Cartesian product of two lists [duplicate]
Asked Answered
P

4

5

I have two lists of strings:

letters = ['abc', 'def', 'ghi']
numbers = ['123', '456']

I want to for loop through them to create a list of strings that is not parallel, so zip() doesn't work here.

Desired outcome:

result = ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']

The order of the elements in the result is irrelevant.

Any ideas?

Plating answered 8/5, 2020 at 11:49 Comment(5)
What's your problem with two nested for loops?Nasho
@Nasho precisely what I was looking for! I just couldn't name it! :)Plating
Does this answer your question? Concatenating Strings: "Multiplication" of two list of stringsAnh
Also: Cartesian product of two lists in pythonAnh
Also: concatenate strings in 2 different lists in pythonAnh
S
12

You can try list comprehension with two nested for loop over numbers and then letters :

print([l+n for n in numbers for l in letters])
# ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']

You can also use nested for loop:

out = []
for n in numbers:
    for l in letters:
        out.append(l+n)
print(out)
# ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']

For more details on list comprehension, see either the doc or this related topic.

Spanjian answered 8/5, 2020 at 11:52 Comment(0)
T
4

Take the product of numbers and letters (rather than letters and numbers), but then join the resulting tuples in reverse order.

>>> from itertools import product
>>> [''.join([y, x]) for x, y in product(numbers, letters)]
['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456']

For 2-tuples, y + x would be sufficient rather than using ''.join.

The product of two lists is just the set of all possible tuples created by taking an element from the first list and an element from the second list, in that order.

>>> list(product(numbers, letters))
[('123', 'abc'), ('123', 'def'), ('123', 'ghi'), ('456', 'abc'), ('456', 'def'), ('456', 'ghi')]
Tommi answered 8/5, 2020 at 11:51 Comment(0)
N
2

Given your lists of prefixes letters and suffixes numbers that have to be combined

letters = ['abc', 'def', 'ghi']
numbers = ['123', '456']

Basic

The first solution that comes to mind (especially if you are new to Python) is using nested loops

result = []
for s in letters:
    for n in numbers:
        result.append(s+n)

and since - as you said - order is irrelevant, also the following will be a valid solution

result = []
for n in numbers:
    for s in letters:
        result.append(s+n)

The most important downside of both is that you need to define the result variable before in a way that looks a bit weak.

Advanced

If you switch to list comprehension you can eliminate that extra line

result = [s+n for n in numbers for s in letters]

Expert

Mathematically spoken, you are creating the Cartesian product of numbers and letters. Python provides a function for exact that purpose by itertools.product (which, by the way, also eliminates the double fors)

from itertools import product
result = [''.join(p) for p in product(letters, numbers)]

this may look like overkill in your very example, but as soon as it comes to more components for building results, it may be a big difference, and all tools presented here but itertools.product will tend to explode then.

For illustration, I conclude with an example that loops over prefixes, infixes, and postfixes:

print([''.join(p) for p in product('ab', '+-', '12')])

that gives this output:

['a+1', 'a+2', 'a-1', 'a-2', 'b+1', 'b+2', 'b-1', 'b-2']
Nasho answered 8/5, 2020 at 13:33 Comment(0)
P
0

Thank you for your answers! I simplified the case, so all of the above solutions work well, however in the real problem I'm working on I want to add more lines of code in between that would iterate through both lists. I completed it nesting those for loops:

for letter in letters:
   for number in numbers:
      print(letter+number)
      # many many lines of more code

Anyway, thanks a lot for your help!

Plating answered 8/5, 2020 at 13:10 Comment(1)
The many many lines of more code should be probably factored out into a function :)Nasho

© 2022 - 2024 — McMap. All rights reserved.