2

我有一个这样的清单:

[['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]

我如何对列表中的元素进行分组,例如上面的?

['0': ['10','11','12']],['1': ['10','11']]
4

3 回答 3

6

迭代 - 放入字典。

d = {}
l = [['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]
for p in l:
    if p[0] in d:
        d[p[0]].append(p[1])
    else:
        d[p[0]] = [p[1]]

>>> d
{'1': ['10', '11'], '0': ['10', '11', '12']}

使用defaultdict

from collections import defaultdict

d = defaultdict(list)
l = [['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]
for p in l:
    d[p[0]].append(p[1])

one-liner:使用dict 理解(有点浪费,但没有导入,需要 2.7+)

>>> dd = {key: [i[1] for i in l if i[0] == key] for (key, value) in l}
>>> dd
{'1': ['10', '11'], '0': ['10', '11', '12']}
于 2012-12-05T09:08:17.457 回答
5

你可以使用collections.defaultdict

import collections

l = [['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]

d = collections.defaultdict(list)
for k, v in l:
    d[k].append(v)
print(d)
于 2012-12-05T09:09:37.177 回答
2

你可以使用dict.setdefault()

In [16]: lis=[['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]

In [17]: dic={}

In [18]: for x,y in lis:
   ....:     dic.setdefault(x,[]).append(y)
   ....:     

In [19]: dic
Out[19]: {'0': ['10', '11', '12'], '1': ['10', '11']}

对于您的列表,甚至itertools.groupby也可以正常工作:

In [39]: from operator import itemgetter

In [40]: from itertools import groupby

In [34]: lis=[['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]

In [35]: {k:[x[1] for x in g] for k,g in groupby(lis,key=itemgetter(0))}
Out[35]: {'0': ['10', '11', '12'], '1': ['10', '11']}
于 2012-12-05T09:11:43.323 回答