Python 对嵌套列表中的项进行分组
如何将此列表中的嵌套列表按其第一个元素分组 例如:Python 对嵌套列表中的项进行分组,python,python-3.x,list,Python,Python 3.x,List,如何将此列表中的嵌套列表按其第一个元素分组 例如: [[12,1],[7,2],[7,3],[7,4],[2,5],[2,6]] ----> [ [12,1], [[7,2],[7,3],[7,4]] , [[2,5],[2,6]] ] 您可以使用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)
[[12,1],[7,2],[7,3],[7,4],[2,5],[2,6]] ---->
[ [12,1], [[7,2],[7,3],[7,4]] , [[2,5],[2,6]] ]
您可以使用
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]]]
[[[12, 1]], [[7, 2], [7, 3], [7, 4]], [[2, 5], [2, 6]]]
您必须使用
itertools
模块中的groupby
功能:
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]]]
[[[12, 1]], [[7, 2], [7, 3], [7, 4]], [[2, 5], [2, 6]]]
对于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]]]
看起来你想让我们为你写些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只在海报已经试图自己解决问题时才提供帮助。展示这一成果的一个好方法是包括您迄今为止编写的代码、示例输入(如果有)、预期输出和实际获得的输出(控制台输出、回溯等)。你提供的细节越多,你可能得到的答案就越多。检查和。