今天早些時候,我需要每次迭代字符串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