我有一个如下所示的列表:
[
[1, "a", 319],
[1, "b", 991],
[2, "Cd", 19],
[3, "88x", 2891],
[3, "foo", 11]
]
最多" pythonic"将此转化为:
[
[1, [["a", 319], ["b", 991]]],
[2, [["Cd", 19]]],
[3, [["88x", 2891], ["foo", 11]]]
]
我知道如何使用for
循环这样做,但是我采用了更清洁的方法。
答案 0 :(得分:3)
这是一个选项,假设列表按照第一个元素排序:
from itertools import groupby
[[k, [x[1:] for x in g]] for k, g in groupby(lst, key = lambda x: x[0])]
#[[1, [['a', 319], ['b', 991]]],
# [2, [['Cd', 19]]],
# [3, [['88x', 2891], ['foo', 11]]]]
答案 1 :(得分:0)
如果您不介意类似字典的对象,也可以使用collections.defaultdict
:
>>> l = [
... [1, "a", 319],
... [1, "b", 991],
... [2, "Cd", 19],
... [3, "88x", 2891],
... [3, "foo", 11]
... ]
>>> import collections
>>> d = collections.defaultdict(list)
>>> for k, *v in l:
... d[k].append(v)
...
>>> import pprint
>>> pprint.pprint(d)
{1: [['a', 319], ['b', 991]],
2: [['Cd', 19]],
3: [['88x', 2891], ['foo', 11]]}