今天早些时候,我需要每次迭代字符串2个字符来解析格式为"+c-R+D-E"
(还有一些额外的字母)的字符串。在Python中一次遍历字符串2(或n)个字符
我结束了这个工作,但它看起来很丑。我最终评论它在做什么,因为它感觉不明显。它几乎似乎pythonic,但不完全。
# Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
是否有一些更好/更干净的方法来做到这一点?
@理查德,可能是你想念一个“)”第2行? – sunqiang 2009-07-22 01:38:21
可能的重复[什么是最“pythonic”的方式来遍历一个列表在块?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate -over-a-list-in-chunks) – 2014-06-28 22:34:10