拆分列表基于共同元素?

时间:2013-10-23 17:33:52

标签: python

我有一大堆包含数据的元组;

test = [
    ('admin', 1, 2),
    ('admin', 3, 4),
    ('admin', 5, 6),
    ('user', 1, 2),
    ('user', 3, 4),
    ('user', 5, 6),
    ('guest', 1, 2),
    ('guest', 3, 4),
    ('guest', 5, 6)
   ]

如何基于元组的element0将它们分成3个独立的迭代? e.g;

[('**admin**', 1, 2),('admin', 3, 4),('admin', 5, 6)]

[('**user**', 1, 2),('user', 3, 4),('user', 5, 6),]

[('**guest**', 1, 2),('guest', 3, 4),('guest', 5, 6)]

提前致谢! 布雷特

3 个答案:

答案 0 :(得分:5)

from collections import defaultdict

buckets = defaultdict(list)
for tup in test:
    buckets[tup[0]].append(tup)

答案 1 :(得分:4)

itertools.groupby与列表理解结合使用:

>>> test = [('admin', 1, 2), ('admin', 3, 4), ('admin', 5, 6), ('user', 1, 2), ('user', 3, 4), ('user', 5, 6), ('guest', 1, 2), ('guest', 3, 4), ('guest', 5, 6)]
>>>
>>> from operator import itemgetter
>>> from itertools import groupby
>>> 
>>> [list(g) for k, g in groupby(sorted(test, key=itemgetter(0)), itemgetter(0))]
[[('admin', 1, 2), ('admin', 3, 4), ('admin', 5, 6)], [('user', 1, 2), ('user', 3, 4), ('user', 5, 6)], [('guest', 1, 2), ('guest', 3, 4), ('guest', 5, 6)]]

答案 2 :(得分:2)

iterables = {}
for x in test:
    iterables.setdefault(x[0], []).append(x)

然后你的iterables是iterables.values()