In C# I can get the sum of some values like so:
new List<Tuple<string, int>>().Sum(x => x.Item2);
How can I achieve the same result in Python? Assuming I have a list of tuples
The equivalent is a comprehension inside a sum()
.
sum(x[1] for x in tuples)
For example, we can define some sample random data.
from random import randint
r = lambda: randint(0, 100)
data = [(r(), r(), r()) for x in range(100)]
sum(x[1] for x in data)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.