事实证明这比我预期的要棘手。我有一个字节字符串:
data = b'abcdefghijklmnopqrstuvwxyz'
我想分块读取这些数据n字节。在 Python 2 下,只需稍加修改即可实现这一点grouper
食谱来自itertools
文档:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return (''.join(x) for x in izip_longest(fillvalue=fillvalue, *args))
有了这个,我可以打电话:
>>> list(grouper(data, 2))
And get:
['ab', 'cd', 'ef', 'gh', 'ij', 'kl', 'mn', 'op', 'qr', 'st', 'uv', 'wx', 'yz']
在 Python 3 下,这变得更加棘手。这grouper
函数如所写
简单地摔倒了:
>>> list(grouper(data, 2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in <genexpr>
TypeError: sequence item 0: expected str instance, int found
这是因为在 Python 3 中,当你迭代一个字节串时(比如b'foo'
),您将得到一个整数列表,而不是一个字节列表:
>>> list(b'foo')
[102, 111, 111]
蟒蛇3bytes
函数将在这里提供帮助:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return (bytes(x) for x in izip_longest(fillvalue=fillvalue, *args))
使用它,我得到了我想要的:
>>> list(grouper(data, 2))
[b'ab', b'cd', b'ef', b'gh', b'ij', b'kl', b'mn', b'op', b'qr', b'st', b'uv', b'wx', b'yz']
但是(当然!)bytes
Python 2 下的函数不工作
一样的方法。这只是一个别名str
,结果是:
>>> list(grouper(data, 2))
["('a', 'b')", "('c', 'd')", "('e', 'f')", "('g', 'h')", "('i', 'j')", "('k', 'l')", "('m', 'n')", "('o', 'p')", "('q', 'r')", "('s', 't')", "('u', 'v')", "('w', 'x')", "('y', 'z')"]
...这根本没有帮助。我最终写了以下内容:
def to_bytes(s):
if six.PY3:
return bytes(s)
else:
return ''.encode('utf-8').join(list(s))
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return (to_bytes(x) for x in izip_longest(fillvalue=fillvalue, *args))
这似乎可行,但这真的是这样做的方法吗?