Iterate over a python sequence in multiples of n?

后端 未结 17 764
北荒
北荒 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

    I am sure someone is going to come up with some more "Pythonic" but how about:

    for y in range(0, len(x), 2):
        print "%s%s" % (x[y], x[y+1])
    

    Note that this would only work if you know that len(x) % 2 == 0;

提交回复
热议问题