Reputation: 1941
I have this array of arrays:
[[[1111, 2222, 3333], [4444, 5555, 6666]], [[7777]], [[8888, 9999]], [[0000]], [[1122, 2233]]]
I need to get all the possible combinations IN ORDER of the elements of the list.
Expected output for this example:
[1111,2222,3333,7777,8888,9999,0000,1122,2233]
[4444, 5555, 6666,7777,8888,9999,0000,1122,2233]
As you may see in this example the first array of the array is the only one who has two options.
I've tried with something like:
for i in array_input:
for j in i:
print ', '.join([str(x) for x in j]),
but that is not getting me the expected output because is firstly iterating through the two array[0] options instead of picking one of them and filling the rest and then picking the other one and filling it.
So I want some loop that gets array[0][0],array[1][0],array[2][0]
... instead of: array[0][0],array[0][1],array[1][0]
...
thank you
Upvotes: 0
Views: 8145
Reputation: 1
list1 = [[[1111, 2222, 3333], [4444, 5555, 6666]], [[7777]], [[8888, 9999]], [[0000]], [[1122, 2233]]]
a = []
for i in list1:
for j in i:
for k in j:
a.append(k)
print(a)
Upvotes: 0
Reputation: 5383
You can just do the following ...
import operator
reduce(operator.__add__, zip(*array_input)[0])
The zip(*array_input)
basically unzips the array to ...
[([1111, 2222, 3333], [7777], [8888, 9999], [0], [1122, 2233])]
zip(*array_input)[0]
simply remove one level of nesting ...
Finally the reduce
operator adds the lists to a single list. You could also have done
reduce(lambda m, n: m+n, zip(*array_input)[0])
but I don't like using lambda functions here ...
Upvotes: 0
Reputation: 1695
You could use itertools.combinations, lets simplify your example to the list `l = ['a', 'b', 'c', 'd'] then you can generate all combinations of length r with:(here i.e. r = 3)
import itertools as it
l = ['a', 'b', 'c', 'd']
for e in it.combinations(l, 3):
print e
=> ('a', 'b', 'c')
('a', 'b', 'd')
('a', 'c', 'd')
('b', 'c', 'd')
if you want to get all combinations just loop your r over the length of l
to overcome the problem with the two arrays you could maybe flatten your list i.e. with something like
new_list = [item for sublist in l for item in sublist]
full example:
import itertools as it
l = [[[1111, 2222, 3333], [4444, 5555, 6666]], [[7777]], [[8888, 9999]], [[0000]], [[1122, 2233]]]
l = [item for sublist in l for item in sublist]
for n in range(1, len(l)):
for e in it.combinations(l, n):
print e
Upvotes: 0
Reputation: 213005
Your elements are integers, so 0000
will be shown as 0
:
import itertools as it
lst = [[[1111, 2222, 3333], [4444, 5555, 6666]], [[7777]], [[8888, 9999]], [[0000]], [[1122, 2233]]]
out = [list(it.chain.from_iterable(x)) for x in it.product(*lst)]
First itertools.product
generates a product of all arguments. Then you need itertools.chain.from_iterable
to flatten the list of lists.
Upvotes: 2