1

I have a code like this:

inp = [['6', '0', '5', '9', '8'], ['='], ['9', '0', '5', '8', '6']]

I want this result:

outp = ['6=9','0=9','5=9' ... '8=8', '8=6']

The size of inp can be different

  • 2
    Possible duplicate of [All combinations of a list of lists](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists) – fedorshishi Feb 16 '19 at 08:30
  • You might find this thread https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists useful, tough you will need to `''.join` your results to get `str`s from `tuple`s – Daweo Feb 16 '19 at 08:31

5 Answers5

3

You can use itertools.product:

from itertools import product
outp = list(map(''.join, product(*inp)))

outp becomes:

['6=9', '6=0', '6=5', '6=8', '6=6', '0=9', '0=0', '0=5', '0=8', '0=6', '5=9', '5=0', '5=5', '5=8', '5=6', '9=9', '9=0', '9=5', '9=8', '9=6', '8=9', '8=0', '8=5', '8=8', '8=6']
blhsing
  • 91,368
  • 6
  • 71
  • 106
2

You want to match each of the items in one list to each of the items in other list. That is a cartesian product. It is implemented in itertools.product

You can do this:

for left, operator, right in product(*inp):
    print ''.join(left, operator, right)
zvone
  • 18,045
  • 3
  • 49
  • 77
0

The Naive and complete solution of the above problem will be fixing each item of a list constant and changing the items of the other two list.

inp = [['6', '0', '5', '9', '8'], ['='], ['9', '0', '5', '8', '6']]
outp = []
for right in inp[2]:
    for oper in inp[1]:
        for left in inp[0]:
            temp = str(left) + str(oper) + str(right)
            outp.append(temp)
print(outp)

Output of the above program :

['6=9', '0=9', '5=9', '9=9', '8=9', '6=0', '0=0', '5=0', '9=0', '8=0', '6=5', '0=5', '5=5', '9=5', '8=5', '6=8', '0=8', '5=8', '9=8', '8=8', '6=6', '0=6', '5=6', '9=6', '8=6']
Vikas Viki
  • 56
  • 4
0
inp = [['6', '0', '5', '9', '8'], ['='], ['9', '0', '5', '8', '6']]
lst =[]
def create_iter(*para):
   for i in range(len(para[0])):
      yield [para[0][i],para[1][0],para[2][i]]


for i in create_iter(*inp):
    lst.append("".join(i))

print(lst)
jamil
  • 26
  • 6
0
from itertools import product
result =[''.join((left, operator, right)) for left,operator,right in product(*inp)]
Akhilesh_IN
  • 1,217
  • 1
  • 13
  • 19