在Python中每次迭代两个(或n个)字符的字符串

40 投票
13 回答
63639 浏览
提问于 2025-04-15 13:04

今天早些时候,我需要每次处理字符串中的两个字符,以便解析一个像 "+c-R+D-E" 这样的格式化字符串(里面还有一些额外的字母)。

我最后写出了这个代码,虽然能用,但看起来不太好。我甚至给它加了注释,因为它的功能不太明显。虽然看起来有点像Python风格,但又不是完全。

# 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

有没有更好或更简洁的方法来实现这个呢?

13 个回答

6
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)
def main():
    s = "+c-R+D-e"
    for item in grouper(s, 2):
        print ' '.join(item)
if __name__ == "__main__":
    main()
##output
##+ c
##- R
##+ D
##- e

izip_longest 这个功能需要 Python 2.6 或更高版本。如果你使用的是 Python 2.4 或 2.5,可以从 这个文档 找到 izip_longest 的定义,或者把分组函数改成:

from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
18

也许这样写会更简洁一些?

s = "+c-R+D-e"
for i in xrange(0, len(s), 2):
    op, code = s[i:i+2]
    print op, code

你可以考虑写一个生成器来实现你想要的功能,也许这样会更符合Python的风格哦 :)

60

我不太了解 cleaner,但还有另外一个选择:

for (op, code) in zip(s[0::2], s[1::2]):
    print op, code

这是一个不需要复制的版本:

from itertools import izip, islice
for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):
    print op, code

撰写回答