如何通过第一个元素将嵌套列表组合在一起?
例如:
[[12,1],[7,2],[7,3],[7,4],[2,5],[2,6]] ---->
[ [12,1], [[7,2],[7,3],[7,4]] , [[2,5],[2,6]] ]
答案 0 :(得分:1)
您必须使用groupby
模块中的itertools
功能:
from itertools import groupby
inList = [[12,1],[7,2],[7,3],[7,4],[2,5],[2,6]]
outList = [list(sub) for ind, sub in groupby(inList, key=lambda i: i[0])]
print(outList)
输出:
[[[12, 1]], [[7, 2], [7, 3], [7, 4]], [[2, 5], [2, 6]]]
答案 1 :(得分:0)
您可以使用itertools.groupby
:
import itertools
s = [[12,1],[7,2],[7,3],[7,4],[2,5],[2,6]]
new_s = list(map(lambda x:x[0] if len(x) == 1 else x, [list(b) for _, b in itertools.groupby(s, key=lambda x:x[0])]))
输出:
[[12, 1], [[7, 2], [7, 3], [7, 4]], [[2, 5], [2, 6]]]
答案 2 :(得分:0)
您可以将collections
库用于O(n)解决方案。在这种情况下,如果订单对您很重要,您可以继承OrderedDict
。
from collections import OrderedDict
lst = [[12,1],[7,2],[7,3],[7,4],[2,5],[2,6]]
class OrderedDefaultListDict(OrderedDict):
def __missing__(self, key):
self[key] = value = []
return value
d = OrderedDefaultListDict()
for i, j in lst:
d[i].append([i, j])
res = list(d.values())
结果:
[[[12, 1]], [[7, 2], [7, 3], [7, 4]], [[2, 5], [2, 6]]]