2D array li available
li = [[1,2],
[2,3],
[3,4],
[4,5],
[1,3],
[1,4]]
I'd like to calculate the sum of the second elements where the first element is 1.
In the above list,
of [1,2][1,3][1,4] the first element is 1.
Calculate the sum of the second elements (2+3+4=9).
I think I can do it if I use filter, map, sum, lambda well...
I'm sorry for the confusing sentence, but I appreciate your cooperation.
python python3
You can use filter, map, but it's not very Pythonic.
filtered=filter(lambdae:e[0]==1,li)
mapped=map(lambdae:e[1], filtered)
print(sum(mapped))
As you mentioned in the comment, it is more concise and recommended (depending on the number of cases).
print(sum(e[1]for e if[0]==1))
Why don't you use numpy.where?
import numpy as np
li = [[1,2],
[2,3],
[3,4],
[4,5],
[1,3],
[1,4]]
m=np.array(li)
idx=np.where(m[:,0]==1)
np.sum(m[idx,1])
The following is an addition.
As for the play level correction, using the Pandas DataFrame, it can be summarized as follows:
import pandas as pd
df = pd.DataFrame(li)
a=df.where(df[0]==1).sum()[1]
Also, the answer in your question is
sum ([e[1]for e in if[0]==1])
The can omit the inclusive notation.
sum(e[1]for e if[0]==1)
This may be more memory-efficient (I've never tried a different size, so I've heard of it), but I'm not going to go into details, but it works as a Python generator.
© 2025 OneMinuteCode. All rights reserved.