Python-将列表列表划分为组 [英] Python - dividing a list-of-lists to groups

查看:219
本文介绍了Python-将列表列表划分为组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下简化情况:

lol = [['John','Polak',5,3,7,9],
       ['John','Polak',7,9,2,3],
       ['Mark','Eden' ,0,3,3,1],
       ['Mark','Eden' ,5,1,2,9]]

将基于前两个参数将此列表列表转换为列表列表的 pythonic和内存+速度高效方法是什么:

What would be a pythonic and memory+speed efficient way to transform this list-of-lists to a list-of-lists-of-lists based on the first two parameters:

lolol = [[['John','Polak',5,3,7,9],
          ['John','Polak',7,9,2,3]],
         [['Mark','Eden' ,0,3,3,1],
          ['Mark','Eden' ,5,1,2,9]]]

实际上-只要我具有正确的层次结构,任何其他数据结构也可以.例如,想到以下字典结构,但是创建它似乎效率不够高效,并且内存可能会比lolol解决方案要高.

Actually - any other data structure would also be ok, as long as I have the correct hierarchy. For example the following dictionary structure comes to mind, but creating it doesn't seem efficient speed-efficient enough, and the memory would probably be higher than the lolol solution.

dolol = {('John','Polak'):[[5,3,7,9],[7,9,2,3]],
         ('Mark','Eden') :[[0,3,3,1],[5,1,2,9]]}

推荐答案

用等效的Python 2补充delnan的答案:

To complement delnan's answer with a Python 2 equivalent:

from collections import defaultdict

dolol=defaultdict(list)
for data in lol:
    dolol[data[0],data[1]].append(data[2:])

这篇关于Python-将列表列表划分为组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆