【发布时间】:2020-03-18 19:49:23
【问题描述】:
给定一个列表L,例如[[1,1,1,1], [1,1,1], [1,1], [1]] 和一个max_len=8,我想创建一个新列表LN,像这样[[[1, 1, 1, 1], [1, 1, 1]], [[1, 1], [1]]]。
所以我有一个列表列表。我想以每个列表的长度总和
我一直在尝试以最 Pythonic 和最有效的方式来做这件事。应该是 O(n)。 在某人的帮助下,这是我到目前为止的代码:
def chunks(list_to_chunck, max_len):
if any(len(sub_list) > max_len for sub_list in list_to_chunck):
return None
new_list = []
while list_to_chunck:
copy_list = [list_to_chunck.pop(0)]
while list_to_chunck:
if len(list_to_chunck[0]) + sum(len(sub_list) for sub_list in copy_list) <= max_len:
copy_list.append(list_to_chunck.pop(0))
else:
break
new_list.append(copy_list)
return new_list
【问题讨论】:
-
请清楚地说明您的代码存在的问题。见minimal, reproducible example。
-
lst.pop(0)会扼杀你的效率。它还改变了作为参数传递的列表,几乎在所有情况下都是反模式(也许是一个小的私有帮助函数,这样做是为了提高效率并且不作为公共 API 的一部分公开,这是可以接受的情况) . -
@Prune 我编辑了更具可读性的代码。