2013-10-20 56 views
-1

我想编写一个函数,它带有一个列表列表,并返回一个列表大小相同的列表。例如,使用[[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]大小不同。但是后来我发现自己正在循环和乱搞索引,这是你通常想避免在Python中做的事情。

那么什么是最快和最Python的方法来做到这一点?

+0

我真不”不要理解为什么人们无缘无故地回答问题。 –

+0

我也一样,一定是因为这是一个初学者的问题。 (如果有什么我应该做的,否则请告诉我) – Emiel

+0

那么Python是非常主观的,也许只是说_fastest_或大多数_efficient_是一个更好的方式来表达它。如果你想要一些东西,可以这么说。或者,如果你想要一个单行列表理解,你也可以这么说:D(这是一个很酷的python特征) –

回答

1

您所需要的逻辑是先子列表的每个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]]] 
1

使用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]]] 
2
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]]] 
1

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

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)   
1
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) 
相关问题