python – tuple inside list for finding values – Education Career Blog

I am list of tuple as:

mylist =  (user1, 23, 32), (user1, 23, 34), (user3, 34, 34), (user2, 34, 45), (user1, 45,23),(user2, 56, 56), (user5, 4,4)

I need to find out average time for each user.
My problem is I dont know how many user are there and values.
So i cannot do

for item in mylist:
    if item0 == 'user1':
       new_list.append( ( item1, item2))

How to get values likes

user1 =  (23,32), (23,34), (45,23)
user2 = (34, 45), (56,56)
usre3 = (34,34)

thanks

,

>>> from collections import defaultdict    
>>> d = defaultdict(list)
>>> for user, *items in mylist:
    duser += items,


>>> d
defaultdict(<class 'list'>, {'user5': 4, 4, 'user2': 34, 45, 56, 56, 'user3': 34, 34, 'user1': 23, 32, 23, 34, 45, 23})

,

You obviously need a dictionary, right? One approach would be like:

results = {}
for user, val1, val2 in mylist:
    if user not in results:
        resultsuser = 
    resultsuser.append((val1, val2))

But thanks to collections.defaultdict (from 2.5 onwards), we can simplify this:

import collections

results = collections.defaultdict(list)
for users, val1, val2 in mylist:
    resultsuser.append((val1, val2))

,

I’m guessing you actually have a list like this:

mylist =  ('user1', 23, 32), ('user1', 23, 34), ('user3', 34, 34), ('user2', 34, 45), ('user1', 45,23), ('user2', 56, 56), ('user5', 4,4)

You don’t want to make a new list, you want a dictionary:

from collections import defaultdict

users = defaultdict(list)
for u, t1, t2 in mylist:
    usersu.append((t1, t2))

Then you can, for example:

print users'user1'

produces:

(23, 32), (23, 34), (45, 23)

,

Use a dictionary:

avgtimes = {}
for item in mylist:
    avgtimes.setdefault(item0, ).append(item1:)

,

from collections import defaultdict
h=defaultdict(list)
mylist =  ("user1", 23, 32), ("user1", 23, 34), ("user3", 34, 34), ("user2", 34, 45), ("user1", 45,23),("user2", 56, 56), ("user5", 4,4)
for item in mylist:
   hitem0.append(item1:)
print h

Leave a Comment