Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lists combination

I have multiple lists:

A=[1,2,3,4,5]
B=[6,7]
C=[8,9,10]

The number of lists and the number of elements in each list can vary.

I am looking for a variable ABC which should contain a list that is a combination of all the values of all the lists, appending from C to B to A (appending from right to left) as shown below. Is there any way that I get this?

ABC=[168,169,1610,178,179,1710,268,269,2610,278,279,2710,........,578,579,5710]

1 Answers

this is a variant:

from itertools import product

ret = [int(f'{a}{b}{c}') for a, b, c in product(A, B, C)]

using itertools.product.


if you need to have that for a variable number of lists you could do this:

lists = [A, B, C]  # D, E, F, ...]
ret = [int(''.join(str(item) for item in items)) for items in product(*lists)]

(alternatively have a look at DSM's version of this in the comments below).

like image 58
hiro protagonist Avatar answered May 30 '26 14:05

hiro protagonist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!