根据python中的第二个列表添加列表中的项目

时间:2018-12-01 10:25:08

标签: python list loops

我有两个清单。我想基于列表颜色在vp中添加值。 所以我想要这个输出:

total = [60,90,60]

因为我希望代码运行以下代码:total = [10+20+30, 40+50,60]

total = []
vp = [10,20,30,40,50,60]
color = [3,2,1]

我不知道该怎么办。我从python3开始这样的事情:

for c, v in zip(color, Vp):
    total.append ....

谢谢

5 个答案:

答案 0 :(得分:2)

您可以对列表进行切片,以根据另一个列表中的内容从原始列表中收集元素,将其加总并追加到最终列表中:

total = []
vp = [10,20,30,40,50,60]
color = [3,2,1]

i = 0
for x in color:
    total.append(sum(vp[i:i+x]))
    i += x

print(total)
# [60, 90, 60]

答案 1 :(得分:1)

此答案对于此示例而言并不理想,但是当您要将密集表示转换为稀疏表示时,它可能对其他情况很有用。在这种情况下,我们使用填充将1D数组转换为2D数组。例如,您希望能够使用np.sum

total = []
vp = [10,20,30,40,50,60]
color = [3,2,1]

# padding (numpy friendly)
max_len = max(color)
vp_with_padding = [
    vp[sum(color[:i]):sum(color[:i])+l] + [0] * (max_len - l)
    for i, l in enumerate(color)
]
# [[10, 20, 30], [40, 50, 0], [60, 0, 0]]
total = np.sum(vp_with_padding, 1)
# similar to:
#total = [sum(x) for x in vp_with_padding]

答案 2 :(得分:0)

total = []
index = 0
for c in color:
  inside = 0
  for i in range(c):
    inside += vp[index + i]
    index += 1
  total.append(inside)
print(total)

答案 3 :(得分:0)

使用列表推导-

vp = [10,20,30,40,50,60]
color = [3,2,1]
commu = np.cumsum(color)    # Get the commulative sum - [3,5,6]
commu = list([0])+list(commu[0:len(commu)-1])    # [0,3,5] and these are the beginning indexes 
total=[sum(vp[commu[i]:commu[i+1]]) if i < (len(range(len(commu)))-1) else sum(vp[commu[i]:]) for i in range(len(commu))]
total
   [60, 90, 60]

答案 4 :(得分:0)

其他选项可建立包含切片的列表,然后映射到总和:

破坏性:

slices = []
for x in color:
  slices.append(vp[0:x])
  del vp[0:x]
sums = [sum(x) for x in slices]

print (sums) #=> [60, 90, 60]

无损:

slices = []
i = 0
for x in color:
  slices.append(vp[i:x+i])
  i += x
sums = [sum(x) for x in slices]

print (sums) #=> [60, 90, 60]