Iteration over list slices

后端 未结 9 636
名媛妹妹
名媛妹妹 2020-11-30 00:59

I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.

In my mind it is something like:

for list_of_x         


        
9条回答
  •  鱼传尺愫
    2020-11-30 01:55

    Use a generator:

    big_list = [1,2,3,4,5,6,7,8,9]
    slice_length = 3
    def sliceIterator(lst, sliceLen):
        for i in range(len(lst) - sliceLen + 1):
            yield lst[i:i + sliceLen]
    
    for slice in sliceIterator(big_list, slice_length):
        foo(slice)
    

    sliceIterator implements a "sliding window" of width sliceLen over the squence lst, i.e. it produces overlapping slices: [1,2,3], [2,3,4], [3,4,5], ... Not sure if that is the OP's intention, though.

提交回复
热议问题