Iterate over a python sequence in multiples of n?

后端 未结 17 767
北荒
北荒 2020-12-01 17:45

How do I process the elements of a sequence in batches, idiomatically?

For example, with the sequence \"abcdef\" and a batch size of 2, I would like to do something

17条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 18:33

    but the more general way would be (inspired by this answer):

    for i in zip(*(seq[i::size] for i in range(size))):
        print(i)                            # tuple of individual values
    

提交回复
热议问题