我是元组列表:
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)]
感谢
答案 0 :(得分: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]]})
答案 1 :(得分: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))
答案 2 :(得分: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)]
答案 3 :(得分:0)
使用字典:
avgtimes = {}
for item in mylist:
avgtimes.setdefault(item[0], []).append(item[1:])
答案 4 :(得分: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