Skip to main content
Code Review

Return to Revisions

4 of 5
fix indentation so code block won't be broken up

Slice a list or NumPy array into consecutive tuples

My function needs two params(a,b) and if...break, which seems redundant. Can it be made prettier?

def slice_list(lst,num):
"""
Given a list or Numpy array,
get consecutive tuples based on specific window. 
"""
 rst = []
 for i,_ in enumerate(lst):
 a = i
 b = i + num
 if len(lst[a:b])<num:
 break
 rst.append(tuple(lst[a:b]))
 return rst

Example:

>>> lst = np.array([10, 11, 12, 13, 26, 28])
>>> slice_list(lst,4)
[(10, 11, 12, 13), (11, 12, 13, 26), (12, 13, 26, 28)]
Jack
  • 171
  • 1
  • 13
lang-py

AltStyle によって変換されたページ (->オリジナル) /