转换列表

时间:2012-12-05 09:02:04

标签: python list

我有一个这样的清单:

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

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

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

3 个答案:

答案 0 :(得分: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])

单线:使用dict comprehension(有点浪费,但没有进口,需要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']}

答案 1 :(得分: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)

答案 2 :(得分: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']}