在Python中执行操作以创建多个子列表

huangapple go评论59阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月7日 17:11:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定