Reputation:
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]
Upvotes: 3
Views: 83
Reputation: 46839
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).
Upvotes: 2
Reputation: 8740
You can also try like this.
Here, you can pass any number of lists of integers (varying in numbers) to function and get the desired list of new numbers.
import itertools
def get_combined_number(*group):
return int("".join(str(num) for num in group))
def get_numbers(*numbers_list):
numbers = []
for group in itertools.product(*numbers_list):
numbers.append(get_combined_number(*group))
return numbers
# Test case 1st
A=[1,2,3,4,5]
B=[6,7]
C=[8,9,10]
numbers = get_numbers(A, B, C) # Any number of arrays/list can be passed
print(numbers) # [168, 169, 1610, 178, 179, 1710, 268, 269, 2610, 278, 279, 2710, 368, 369, 3610, 378, 379, 3710, 468, 469, 4610, 478, 479, 4710, 568, 569, 5610, 578, 579, 5710]
# Test case 2nd
D = [1, 4, 9]
E = [2, 7, 1729]
F = [8, 9,11]
G = [ 45, 92, 4, 12, 67]
numbers = get_numbers(D, E, F, G)
print(numbers) # [12845, 12892, 1284, 12812, 12867, 12945, 12992, 1294, 12912, 12967, 121145, 121192, 12114, 121112, 121167, 17845, 17892, 1784, 17812, 17867, 17945, 17992, 1794, 17912, 17967, 171145, 171192, 17114, 171112, 171167, 11729845, 11729892, 1172984, 11729812, 11729867, 11729945, 11729992, 1172994, 11729912, 11729967, 117291145, 117291192, 11729114, 117291112, 117291167, 42845, 42892, 4284, 42812, 42867, 42945, 42992, 4294, 42912, 42967, 421145, 421192, 42114, 421112, 421167, 47845, 47892, 4784, 47812, 47867, 47945, 47992, 4794, 47912, 47967, 471145, 471192, 47114, 471112, 471167, 41729845, 41729892, 4172984, 41729812, 41729867, 41729945, 41729992, 4172994, 41729912, 41729967, 417291145, 417291192, 41729114, 417291112, 417291167, 92845, 92892, 9284, 92812, 92867, 92945, 92992, 9294, 92912, 92967, 921145, 921192, 92114, 921112, 921167, 97845, 97892, 9784, 97812, 97867, 97945, 97992, 9794, 97912, 97967, 971145, 971192, 97114, 971112, 971167, 91729845, 91729892, 9172984, 91729812, 91729867, 91729945, 91729992, 9172994, 91729912, 91729967, 917291145, 917291192, 91729114, 917291112, 917291167]
Upvotes: 0