Waterploof
Waterploof

Reputation: 101

Add items from a list based on a second list in python

I have two list. I want add values in vp based on the list color. So I want this output:

total = [60,90,60]

Because I want that the code runs what follows: total = [10+20+30, 40+50,60]

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

I don't know how to do. I began something like this in python3:

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

thank you

Upvotes: 2

Views: 163

Answers (5)

iGian
iGian

Reputation: 11203

Other option build a list with slices then map to sum:

Destructive:

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]

Non destructive:

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]

Upvotes: 0

cph_sto
cph_sto

Reputation: 7607

Using List comprehensions -

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]

Upvotes: 0

Mehdi
Mehdi

Reputation: 4318

This answer is not ideal for this example but it might be useful for other situations when you want to convert a dense representation to sparse representation. In this case, we convert the 1D array to 2D array with padding. For example, you want to be able to use 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]

Upvotes: 1

Austin
Austin

Reputation: 26057

You can play with some slicing through lists to gather elements from original list based on content in another list, sum it up and append to final list:

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]

Upvotes: 2

Sai Sriharsha Annepu
Sai Sriharsha Annepu

Reputation: 82

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)

Upvotes: 0

Related Questions