How to concatenate an indefinite number of item lists in python

If I have an undefined number of lists and I want to write a method to concatenate them in different ways, what would be the best way to do this? So I don’t have only 2 lists, such as list A and list B, and you can write something like

X = [x+y for x, y in zip(A, B)]

but I will have different generated lists that need to be concatenated sequentially, so I don’t know how to iterate over n number of lists and combine them.

The first list will always have one or more elements ( its length may be different ), and those that after it will always contain only one element:

['a','b','c'],['foo'], ['bar']....

As a result i need

['afoobar','bfoobar','cfoobar']
+4
2

. itertools.product str.join.

>>> from itertools import product
>>> lists = [['a','b','c'],['foo'], ['bar']]
>>> [''.join(x) for x in product(*lists)]
['afoobar', 'bfoobar', 'cfoobar']

( product(*lists) product, )

+2
from itertools import product

[''.join(prod) for prod in product(['a','b','c'],['foo'], ['bar'])]

# ['afoobar', 'bfoobar', 'cfoobar']

:

[''.join(prod) for prod in product(['a','b','c'],
                                   ['foo1_', 'foo2_'],
                                   ['bar'], ['end'])]
# ['afoo1_barend',
#  'afoo2_barend',
#  'bfoo1_barend',
#  'bfoo2_barend',
#  'cfoo1_barend',
#  'cfoo2_barend']
+4

Source: https://habr.com/ru/post/1674572/


All Articles