-1
爲了更準確:如何將列表分組成一個包含順序的n長度子列表?
A = [1, 2, 3, 4, 5, 6, 7]
def group_me(A, 4):
# magic goes here
---> [1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]
任何想法?
爲了更準確:如何將列表分組成一個包含順序的n長度子列表?
A = [1, 2, 3, 4, 5, 6, 7]
def group_me(A, 4):
# magic goes here
---> [1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]
任何想法?
試試這個:
def group_me(array,length):
return [array[n:n+length] for n in range(0,len(array)-length+1)]
使用列表理解
def group_me(A, n):
return [A[i:i+n] for i in range(len(A)-n+1)]
>>> group_me([1, 2, 3, 4, 5, 6, 7], 4)
[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]