I have a list of items with the "Type" and "Time" properties that I want to quickly add up the time for each "Type" and add it to another list. The list is as follows:
Items = [{'Name': A, 'Type': 'Run', 'Time': 5}, {'Name': B, 'Type': 'Walk', 'Time': 15}, {'Name': C, 'Type': 'Drive', 'Time': 2}, {'Name': D, 'Type': 'Walk', 'Time': 17}, {'Name': E, 'Type': 'Run', 'Time': 5}]
I want to do something that works like this:
Travel_Times=[("Time_Running","Time_Walking","Time_Driving")] Run=0 Walk=0 Drive=0 for I in Items: if I['Type'] == 'Run': Run=Run+I['Time'] elif I['Type'] == 'Walk': Walk=Walk+I['Time'] elif I['Type'] == 'Drive': Drive=Drive+I['Time'] Travel_Times.append((Run,Walk,Drive))
With Travel_Times , it finally looks like this:
print(Travel_Times) [("Time_Running","Time_Walking","Time_Driving") (10,32,2)]
This is similar to what should be easy to do efficiently with list comprehension or something similar to collections.Counter , but I can't figure it out. The best way I understood is to use a separate list comprehension for each "Type", but this requires repeated repetition in the list. I would appreciate any ideas on how to speed it up.
thanks