问题描述
如何以惯用方式批量处理序列的元素?
How do I process the elements of a sequence in batches, idiomatically?
例如,使用序列abcdef且批量大小为2,我会喜欢做类似以下的事情:
For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:
for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
当然,这不起作用,因为它期望列表中的单个元素本身包含2个元素。
Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.
什么是好的,短的,干净,pythonic方法来处理批处理中列表的下n个元素,或者来自更大字符串的长度为n的子字符串(两个类似的问题)?
What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?
推荐答案
我相信有人会想出更多Pythonic但是怎么样:
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])
请注意,这仅在您知道 len(x)%2 == 0;
Note that this would only work if you know that len(x) % 2 == 0;
这篇关于以n的倍数迭代一个python序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!