英文:
Creating multiple sublists by performing an operation in Python
问题
当前的输出是:
[0.0, 0.9979508721068377, 0.9961113206802571, 0.9979508721068377, 0.0, 0.0]
期望的输出是:
[[0.0, 0.9979508721068377, 0.9961113206802571], [0.9979508721068377, 0.0, 0.0]]
英文:
I have two lists A2
and Cb_new
. I am performing an operating as shown below. But I want to create multiple sublists instead of one single list. I present the current and expected outputs.
A2=[[2, 3, 5], [3, 4, 6]]
Cb_new=[[1.0, 0.0, 0.0, 0.9979508721068377, 0.0, 0.9961113206802571, 0.0, 0.0, 0.996111320680257, 0.0, 0.0]]
Cb=[]
for j in range(0,len(A2)):
for i in range(0,len(A2[j])):
Cb1=Cb_new[0][A2[j][i]]
Cb.append(Cb1)
print(Cb)
The current output is
[0.0, 0.9979508721068377, 0.9961113206802571, 0.9979508721068377, 0.0, 0.0]
The expected output is
[[0.0, 0.9979508721068377, 0.9961113206802571], [0.9979508721068377, 0.0, 0.0]]
答案1
得分: 1
您需要使用临时列表来实现这种行为。在您的代码中,Cb1始终是Cb_new列表中的一个元素。相反,您应该将它附加到一个在外部for循环的每次迭代中重置的列表中。
for j in range(0,len(A2)):
Cb_interm = []
for i in range(0,len(A2[j])):
Cb1=Cb_new[0][A2[j][i]]
Cb_interm.append(Cb1)
Cb.append(Cb_interm)
print(Cb)
输出结果:
[[0.0, 0.9979508721068377, 0.9961113206802571], [0.9979508721068377, 0.0, 0.0]]
英文:
You will need to use a temporary list to achieve this behavior. In your code Cb1 is always an element from Cb_new list. Instead, you should append it to a list that you reset at every iteration of outer for loop.
for j in range(0,len(A2)):
Cb_interm = []
for i in range(0,len(A2[j])):
Cb1=Cb_new[0][A2[j][i]]
Cb_interm.append(Cb1)
Cb.append(Cb_interm)
print(Cb)
The output:
[[0.0, 0.9979508721068377, 0.9961113206802571], [0.9979508721068377, 0.0, 0.0]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论