Python:有没有办法将一串数字分成每个第三个数字?

Kyl*_*e W 6 python list

例如,如果我有一个字符串a = 123456789876567543我可以有一个类似的列表...

123 456 789 876 567 543

Miz*_*zor 10

>>> a="123456789"
>>> [int(a[i:i+3]) for i in range(0, len(a), 3)]
[123, 456, 789]
Run Code Online (Sandbox Code Playgroud)


mil*_*s82 6

来自itertools文档的配方(当长度不是3的倍数时,您可以定义fillvalue):

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

s = '123456789876567543'

print [''.join(l) for l in grouper(3, s, '')]


>>> ['123', '456', '789', '876', '567', '543']
Run Code Online (Sandbox Code Playgroud)


Tam*_*más 2

s = str(123456789876567543)
l = []
for i in xrange(0, len(s), 3):
    l.append(int(s[i:i+3]))
print l
Run Code Online (Sandbox Code Playgroud)