2010-10-20 57 views
3

我的元組的名單爲:元組列表內尋找價值

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: 
    if item[0] == 'user1': 
     new_list.append((item1, item2)) 

如何獲得值喜歡

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

感謝

回答

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


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

啊,順序un包裝......天才! +1 – delnan 2010-10-20 12:27:00

+0

+1我從來沒有在for循環中看到序列解包! – rubik 2010-10-20 12:35:58

+0

for python 3. *,你會在python 2中得到一個語法錯誤。* – mouad 2010-10-20 13:25:45

2

你顯然需要一個字典,對嗎?一種方法是這樣的:

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

但由於collections.defaultdict(從2.5起),我們可以簡化這個:

import collections 

results = collections.defaultdict(list) 
for users, val1, val2 in mylist: 
    results[user].append((val1, val2)) 
+0

感謝它在2.5幫助.. – laspal 2010-10-20 18:03:48

0

我猜你確實有這樣的名單:

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

你不想做一個新的列表,想要一本字典:

from collections import defaultdict 

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

然後你就可以,例如:

print users['user1'] 

生產:

[(23, 32), (23, 34), (45, 23)] 
0

使用詞典:

avgtimes = {} 
for item in mylist: 
    avgtimes.setdefault(item[0], []).append(item[1:]) 
0
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: 
    h[item[0]].append(item[1:]) 
print h