我有这样的代码:
inp = [['6', '0', '5', '9', '8'], ['='], ['9', '0', '5', '8', '6']]
我想要这个结果:
outp = ['6=9','0=9','5=9' ... '8=8', '8=6']
inp的大小可以不同
答案 0 :(得分:3)
您可以使用itertools.product
:
from itertools import product
outp = list(map(''.join, product(*inp)))
outp
变为:
['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']
答案 1 :(得分:2)
您要将一个列表中的每个项目与另一个列表中的每个项目进行匹配。那是笛卡尔积。它是在itertools.product
您可以这样做:
for left, operator, right in product(*inp):
print ''.join(left, operator, right)
答案 2 :(得分:0)
上述问题的幼稚而完整的解决方案是修复列表常量的每个项目并更改其他两个列表的项目。
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)
上述程序的输出:
['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']
答案 3 :(得分: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)
答案 4 :(得分:0)
object