我有两个清单:
xi_rppi = [[0.4404518],
[0.35042380000000001,
0.41857349999999999,
0.087422100000000003,
0.32525920000000003,
0.31717889999999999,
0.41572910000000002],
[0.32572420000000002,
0.2707909,
0.37550240000000001,
0.40988249999999998,
0.36942079999999999,
0.39833210000000002,
0.34174739999999998]]
pi = [[1.0558920000000001],
[1.0558920000000001,
1.1739245,
1.3051515,
1.451047,
1.613251,
1.7935875000000001],
[1.0558920000000001,
1.1739245,
1.3051515,
1.451047,
1.613251,
1.7935875000000001,
1.9940829999999998]]
例如,当我想将xi_rppi[1]
与pi[1]
相乘时,我可以这样做:
[a*b for a,b in zip(xi_rppi[1],pi[1])]
但我希望将整个列表xi_rppi
与pi
相乘。当我尝试上述方法时,我可以出错:
TypeError: can't multiply sequence by non-int of type 'list'
答案 0 :(得分:2)
我不确定你想要一个扁平的输出或嵌套的输出,但看看这是否有意义 -
print([ a*b for xi_rppi_instance,pi_instance in zip(xi_rppi,pi) for a,b in zip(xi_rppi_instance,pi_instance)])
这是一个双for循环问题,我在列表解析中使用了两个for
循环。样本输出会有所帮助!
答案 1 :(得分:2)
您可以尝试以下代码
print [[a*b for a,b in zip(xi_rppi[i],pi[i])] for i in range(len(xi_rppi))]
答案 2 :(得分:1)
您需要的是两个for
循环:
result = [ [a*b for a,b in zip(e1,e2) ] for e1,e2 in zip(xi_rppi,pi) ]
result
将是:
[[0.46506953200560003],
[0.3700096870296,
0.49137368670075,
0.11409908494815,
0.4719663863824,
0.5116891776039,
0.7456465171462501],
[0.34392957698640003,
0.31788807188705004,
0.4900875206136,
0.5947587719774999,
0.5959684750208,
0.7144434754087501,
0.6814726806341999]]
答案 3 :(得分:1)
一线解决方案:
print([[sub_item[0] * sub_item[1] for sub_item in zip(item[0], item[1])] for item in zip(xi_rppi,pi)])
输出:
[[0.46506953200560003], [0.3700096870296, 0.49137368670075, 0.11409908494815, 0.4719663863824, 0.5116891776039, 0.7456465171462501], [0.34392957698640003, 0.31788807188705004, 0.4900875206136, 0.5947587719774999, 0.5959684750208, 0.7144434754087501, 0.6814726806341999]]
详细解决方案:
以上列表理解与:
相同final=[]
for item in zip(xi_rppi,pi):
semi_final=[]
for sub_item in zip(item[0],item[1]):
semi_final.append(sub_item[0]*sub_item[1])
final.append(semi_final)
print(final)