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

5 Answers 5

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']
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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']

Comments

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)

1 Comment

Please don't just dump code as an answer, explain what your code does and how it solves the problem of the question.
0
from itertools import product
result =[''.join((left, operator, right)) for left,operator,right in product(*inp)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.