我想(出于學習目的,但如果有內置函式可以做到這一點,請告訴我)定義一個函式,該函式需要:
- 輸入:一個串列
[x_1, ... x_k] - 輸入:一個數字
n
并回傳串列串列:
- 輸出:
[ [x_1...x_n], [x_n 1,...m x_n n], ...... [...x_k] ]
這基本上將輸入串列“拆分”為大小串列n,(最后一個串列允許具有較小的大小)。
示例 1:f([1,2,3,4,5,6,7],2) = [[1,2], [3,4] , [5,6], [7] ]
示例 2:f([1,2],2) = [ [1,2] ]
示例 3:f([1],2) = [ [1] ]
示例 4:f([]) = [ [] ]
我嘗試按如下方式實作該功能:
def split_in_pieces(l,n): # Split a list into a list of lists, each of size n (the last one can be smaller).
if len(l) <= n:
return [l]
else:
tail = l[n:]
recursive_result = split_in_pieces(tail, n) # Recursively split the rest of the list.
# Now return the list with the first element,
# concatenated with the recursive result
return recursive_result.insert(0,l[:n])
但是,此代碼不起作用。如果我嘗試:
r = split_in_pieces(range(30),2)
我收到以下錯誤:
AttributeError: 'NoneType' object has no attribute 'insert'
有人可以幫助了解發生了什么嗎?
謝謝!
uj5u.com熱心網友回復:
該insert()方法就地修改串列并回傳None。您需要回傳recursive_result:
def split_in_pieces(l,n): # Split a list into a list of lists, each of size n (the last one can be smaller).
if len(l) <= n:
return [l]
else:
tail = l[n:]
recursive_result = split_in_pieces(tail, n) # Recursively split the rest of the list.
# Now return the list with the first element,
# concatenated with the recursive result
recursive_result.insert(0,l[:n])
return recursive_result
uj5u.com熱心網友回復:
沒有內置函式(據我所知)可以做到這一點。但是,使用串列推導很容易實作 - 即,不需要遞回。
例如:
def split_in_pieces(lst, n):
return [lst[offset:offset n] for offset in range(0, len(lst), n)]
print(split_in_pieces(list(range(10)), 2))
輸出:
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448678.html
上一篇:將孩子放在一個串列中
