-3

I tried to do something like below:

a_list = [
    range(1, 4),
    range(5, 8),
    range(11, 14),
]

I wanted a result like that:

res = ['1 5 11', '1 5 12', '1 5 13', '1 6 11', '1 6 12', '1 6 13', '1 7 11', '1 7 12', '1 7 13',
       '2 5 11', '2 5 12', '2 5 13', '2 6 11', '2 6 12', '2 6 13', '2 7 11', '2 7 12', '2 7 13',
       '3 5 11', '3 5 12', '3 5 13', '3 6 11', '3 6 12', '3 6 13', '3 7 11', '3 7 12', '3 7 13',
      ]

How can I get it

Nayeem
  • 53
  • 1
  • 5

3 Answers3

2

What you're looking for is the Cartesian product of the sublists.

from itertools import product

a_list = [
    ['1', '2', '3'],
    ['5', '6', '7'],
    ['11', '12', '13'],
]

list(product(*a_list))

That will give you a list of tuples. If you need a list of lists instead, try:

[list(x) for x in product(*a_list)]

And finally if you want space separated strings:

[' '.join(x) for x in product(*a_list)]
Seananigan
  • 43
  • 4
Charles
  • 3,116
  • 2
  • 11
  • 20
2

Combining itertools.product and ' '.join you can do it

from itertools import product
# product(*a_list) [('1', '5', '11'), ('1', '5', '12'), ('1', '5', '13'), ...
prod = map(' '.join, product(*a_list)) # ['1 5 11', '1 5 12', '1 5 13', '1 6 11', ...
print(list(prod))
azro
  • 53,056
  • 7
  • 34
  • 70
0
import itertools
a_list = [
    ['1', '2', '3'],
    ['5', '6', '7'],
    ['11', '12', '13'],
]

b_list = [' '.join(i) for i in itertools.product(*a_list)]
print(b_list)

Result is:

['1 5 11', '1 5 12', '1 5 13', '1 6 11', '1 6 12', '1 6 13', '1 7 11', '1 7 12', '1 7 13', '2 5 11', '2 5 12', '2 5 13', '2 6 11', '2 6 12', '2 6 13', '2 7 11', '2 7 12', '2 7 13', '3 5 11', '3 5 12', '3 5 13', '3 6 11', '3 6 12', '3 6 13', '3 7 11', '3 7 12', '3 7 13']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Bill Chen
  • 1,699
  • 14
  • 24