Reputation: 65
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
Upvotes: 1
Views: 74
Reputation: 1327
from itertools import product
result =[''.join((left, operator, right)) for left,operator,right in product(*inp)]
Upvotes: 0
Reputation: 26
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)
Upvotes: 0
Reputation: 56
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']
Upvotes: 0
Reputation: 19352
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)
Upvotes: 2
Reputation: 106553
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']
Upvotes: 3