Home > OS >  Map duplicate entries in an list to a single value
Map duplicate entries in an list to a single value

Time:08-17

I'm working on a program that can track employee performance over four different floors of a building. It takes a list of users and these users are mapped to a floor. Occasionally the same user may cover 2 or even 3 of the floors. When this happens I want the task to be credited to the user regardless of what floor they are on. An example of this is the following:

users = ['David','David','Noah','Jenny']
tasksCompleted = [5,5,4,6]



desiredOutput = [10,10,4,6]

In this case, the desired output is 10 for index 0 and 1 because 5 tasks were completed on the first two floors that were covered by 'David'

My question is how do I achieve this? I've been stuck on this problem for a few days, and I'm having trouble finding out the answer. I've only gotten serious about using Python about a month ago, and this may not even be the best way to go about this problem. Any help, or advice would be greatly appreciated.

CodePudding user response:

users = ['David','David','Noah','Jenny']
tasksCompleted = [5, 5, 4, 6]
totalCompleted = {user: 0 for user in users}
for user, task in zip(users, tasksCompleted):
    totalCompleted[user]  = task
desiredOutput = [totalCompleted[user] for user in users]
print(desiredOutput)

prints

[10, 10, 4, 6]

CodePudding user response:

You can use a simple loop with zip:

d = {}
for u,t in zip(users, tasksCompleted):
    d[u] = d.get(u,0)   t

out = [d[u] for u in users]

Output: [10, 10, 4, 6]

Intermediate d:

{'David': 10, 'Noah': 4, 'Jenny': 6}
  • Related