问题
In my dictionary, each entry has a list of tuples (my python grammar may be wrong, please bear with me). It looks something like this:
{1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)],...}
I'd like to sum the second value in the tuple for each entry, i.e.:
{1: (10), 2: (5)...}
I have been using different forms of
result = sum(y for v in dict.itervalues() for (x, y) in v)
But it adds up all of the values for both entries.
回答1:
You can do something like this:
Edit: Thanks to @ vaultah's comment.
a = {1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)]}
final = {k:(sum(j for _,j in v),) for k,v in a.items()}
print(final)
Output:
>>> {1: (10,), 2: (6,)}
回答2:
sum = 0
for item in dict:
for _,x in dict[item]:
sum = sum + x
print sum
回答3:
Another way to solve it using map/lambda
:
result = {k: sum(map(lambda x: x[1], v)) for k, v in dict.items()}
来源:https://stackoverflow.com/questions/43400223/python-sum-values-in-tuple-in-a-list-in-a-dictionary