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

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

Creating multiple sublists by performing an operation in Python

问题

当前的输出是:

  1. [0.0, 0.9979508721068377, 0.9961113206802571, 0.9979508721068377, 0.0, 0.0]

期望的输出是:

  1. [[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.

  1. A2=[[2, 3, 5], [3, 4, 6]]
  2. Cb_new=[[1.0, 0.0, 0.0, 0.9979508721068377, 0.0, 0.9961113206802571, 0.0, 0.0, 0.996111320680257, 0.0, 0.0]]
  3. Cb=[]
  4. for j in range(0,len(A2)):
  5. for i in range(0,len(A2[j])):
  6. Cb1=Cb_new[0][A2[j][i]]
  7. Cb.append(Cb1)
  8. print(Cb)

The current output is

  1. [0.0, 0.9979508721068377, 0.9961113206802571, 0.9979508721068377, 0.0, 0.0]

The expected output is

  1. [[0.0, 0.9979508721068377, 0.9961113206802571], [0.9979508721068377, 0.0, 0.0]]

答案1

得分: 1

  1. 您需要使用临时列表来实现这种行为在您的代码中Cb1始终是Cb_new列表中的一个元素相反您应该将它附加到一个在外部for循环的每次迭代中重置的列表中
  2. for j in range(0,len(A2)):
  3. Cb_interm = []
  4. for i in range(0,len(A2[j])):
  5. Cb1=Cb_new[0][A2[j][i]]
  6. Cb_interm.append(Cb1)
  7. Cb.append(Cb_interm)
  8. print(Cb)
  9. 输出结果:
  10. [[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.

  1. for j in range(0,len(A2)):
  2. Cb_interm = []
  3. for i in range(0,len(A2[j])):
  4. Cb1=Cb_new[0][A2[j][i]]
  5. Cb_interm.append(Cb1)
  6. Cb.append(Cb_interm)
  7. print(Cb)

The output:

  1. [[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:

确定