[英]Split List into Equal Chunks and Append Last sublist to Previous sublists
[英]How to split list into equal sublists with the last sublist made up from the first possible elements of the list
我想將列表拆分為指定長度的子列表。 如果最后一塊不是指定的長度,將從列表的第一個元素開始增加。
下面的Python程序產生除最后一塊以外的相等子列表。
def split_list(the_list, chunk_size):
result_list = []
while the_list:
result_list.append(the_list[:chunk_size])
the_list = the_list[chunk_size:]
return result_list
a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print split_list(a_list, 3)
輸出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
我想要這樣的東西:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
讓我們嘗試使用itertools.cycle
和islice
的基於生成器的解決方案:
from itertools import cycle, islice
def split_list(lst, n):
it = cycle(lst)
for i in range(len(lst) // n + len(lst) % n):
yield list(islice(it, n))
像這樣調用函數:
>>> a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(split_list(a_list, 3))
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
我個人更喜歡使用生成器,因為可以一次高效地生成一個塊。 如果您一次想要所有內容,則可以在結果上調用list()
(就像我做的那樣)。
檢查最后一個列表塊中是否缺席。 如果是這樣,請精確添加所需數量的元素,重復數量從列表的開頭開始。
def split_list(the_list, chunk_size):
result_list = []
short = len(the_list) % chunk_size
if short:
# Add wrap-around elements from front of the_list
the_list.extend(the_list[:chunk_size-short])
while the_list:
result_list.append(the_list[:chunk_size])
the_list = the_list[chunk_size:]
return result_list
a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(split_list(a_list, 3))
輸出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
一種方法是使用列表推導,然后根據需要將列表開頭的一部分添加到最終組中。
def split_list(the_list, chunk_size):
chunks = [the_list[i:i+chunk_size] for i in range(0, len(the_list), chunk_size)]
chunks[-1] += the_list[:(chunk_size - len(the_list)) % chunk_size]
return chunks
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.