繁体   English   中英

将列表列表转换为长度相同的列表的更嵌套列表的最佳方法?

[英]Best way to turn a list of lists into a more nested list of lists of lists with equal length?

我想编写一个函数,该函数接受一个列表列表,并返回一个列表,列表的大小相等。 例如,使用[[1,2], [0,1], [1,2,3], [0,1,2], [1,2,3,4]]作为输入,该函数应返回[[[1,2],[0,1]], [[1,2,3],[0,1,2]], [[1,2,3,4]]] 我知道最长的名单的长度。

我的第一个直觉是为此使用列表理解:

def nestedlenlist(biglist,maxlen):
    return [[lists for lists in biglist if len(lists) == n] for n in xrange(0,maxlen)]

我对此有两个看法:

  1. 它会遍历整个列表的maxlen时间,而较长的列表可能会花费一些时间。
  2. 如果我不知道列表的最大长度怎么办?

一个解决方案可能涉及sorted :首先对列表进行排序,以便您只需要遍历列表一次,只要biglist[i]biglist[i+1]的大小不同, biglist[i+1]其拆分。 但是然后我发现自己在索引中循环和混乱,这是您通常希望避免在Python中执行的操作。

那么最快和最Python化的方法是什么呢?

In [1]: x =[[1,2], [0,1], [1,2,3], [0,1,2], [1,2,3,4]]

In [2]: result = {}

In [3]: for xx in x: result.setdefault(len(xx),[]).append(xx)

In [4]: result.values()
Out[4]: [[[1, 2], [0, 1]], [[1, 2, 3], [0, 1, 2]], [[1, 2, 3, 4]]]

使用collections.defaultdict

>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> lis = [[1,2], [0,1], [1,2,3], [0,1,2], [1,2,3,4]]
>>> for item in lis:
...     dic[len(item)].append(item)
...     
>>> dic.values()  # use `sorted` if you want result to be sorted by `len`
[[[1, 2], [0, 1]], [[1, 2, 3], [0, 1, 2]], [[1, 2, 3, 4]]]

或使用itertools.groupby

>>> from itertools import groupby
>>> lis = [[1,2], [0,1], [1,2,3], [0,1,2], [1,2,3,4]]
>>> sorted_lis = sorted(lis, key=len)  #sort the list based on length of items
>>> [list(g) for k, g in groupby(sorted_lis, key=len)]  
[[[1, 2], [0, 1]], [[1, 2, 3], [0, 1, 2]], [[1, 2, 3, 4]]]

您需要的逻辑是首先迭代列表,将子列表的每个len组成一个组,然后简单地将所有内容放到一个列表中。 这也会对它们进行排序。 但是,如果您想走得更快,则可以不做任何事情。

from collections import defaultdict

def bucket_list(nested_list, sort=True):
    bucket = defaultdict(list)
    for sublist in nested_list:
        bucket[len(sublist)].append(sublist)
    return [v for k,v in sorted(bucket.items())] if sort else bucket.values()

使用它:

>>> bucket_list([[1,2], [0,1], [1,2,3], [0,1,2], [1,2,3,4]])
[[[1, 2], [0, 1]], [[1, 2, 3], [0, 1, 2]], [[1, 2, 3, 4]]]

这是一个纯粹的列表理解解决方案,但不是最好的(我认为):

origin = [[1, 2], [0, 1], [1, 2, 3], [0, 1, 2], [1, 2, 3, 4], [1]]


def list_of_lists(some_list):
    """
    This is a weird algorithm
    @type some_list: list
    @rtype : list
    @param some_list:
    """
    if len(some_list) % 2:
        return [[a, b] for a, b in zip(some_list[::2], (some_list[1::2]))] + [some_list[len(origin) - 1]]
    else:
        return [[a, b] for a, b in zip(some_list[::2], (some_list[1::2]))]

if __name__ == '__main__':
    print list_of_lists(origin)        
lens = [len(x) for x in biglist]
longest = max(lens)

# Need to make sure that the list of lists is not shallow copies
newlist = []
for n in range(longest):
    newlist.append 

for alist in biglist:
   x = len(alist) - 1
   newlist[x].append(alist)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM