Home > Mobile >  Trying to add items in list of lists of tuples
Trying to add items in list of lists of tuples

Time:08-12

I am making a game picking app and I am stuck on trying to get a summary of points for users. The list is consisting of 18 lists (weeks) with all users and their respective points, sorted alphabetically. I don't know how to create a list with user---> all points combined.

Here is an example with only 2 users

[[('user1', 25), ('user2 ', 18)], [('user1', 18), ('user2 ', 25)], [('user1', 18), ('user2 ', 25)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)]]

CodePudding user response:

That's what I'd suggest:

from collections import Counter

data = [[('user1', 25), ('user2 ', 18)], [('user1', 18), ('user2 ', 25)], [('user1', 18), ('user2 ', 25)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)]]

user_points = Counter()
for week in data:
    for user, points in week:
        user_points[user]  = points

print(user_points) # Counter({'user2 ': 68, 'user1': 61})

CodePudding user response:

This solution should work:

data = your_list
out = {}

for week in data:
    for user in week:
        if user[0] in out.keys():
            out[user[0]]  = user[1]
        else:
            out[user[0]] = user[1]

print(out) # Just in case you want to try

CodePudding user response:

You can do it with zip and dict comprehensions

lst = [[('user1', 25), ('user2 ', 18)], [('user1', 18), ('user2 ', 25)], [('user1', 18), ('user2 ', 25)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)], [('user1', 0), ('user2 ', 0)]]
d = {x[0][0]: sum(list(zip(*x))[1]) for x in zip(*lst)}
print(d) # {'user1': 61, 'user2 ': 68}
  • Related