Iteration over list slices

后端 未结 9 645
名媛妹妹
名媛妹妹 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:54

    For a near-one liner (after itertools import) in the vein of Nadia's answer dealing with non-chunk divisible sizes without padding:

    >>> import itertools as itt
    >>> chunksize = 5
    >>> myseq = range(18)
    >>> cnt = itt.count()
    >>> print [ tuple(grp) for k,grp in itt.groupby(myseq, key=lambda x: cnt.next()//chunksize%2)]
    [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14), (15, 16, 17)]
    

    If you want, you can get rid of the itertools.count() requirement using enumerate(), with a rather uglier:

    [ [e[1] for e in grp] for k,grp in itt.groupby(enumerate(myseq), key=lambda x: x[0]//chunksize%2) ]
    

    (In this example the enumerate() would be superfluous, but not all sequences are neat ranges like this, obviously)

    Nowhere near as neat as some other answers, but useful in a pinch, especially if already importing itertools.

提交回复
热议问题