0

我有大量包含数据的元组;

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 个单独的迭代?例如;

[('**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)]

提前致谢!布雷特

4

3 回答 3

5
from collections import defaultdict

buckets = defaultdict(list)
for tup in test:
    buckets[tup[0]].append(tup)
于 2013-10-23T17:37:00.983 回答
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)]]
于 2013-10-23T17:39:03.727 回答
2
iterables = {}
for x in test:
    iterables.setdefault(x[0], []).append(x)

然后你的迭代是iterables.values().

于 2013-10-23T17:37:46.097 回答