如何让Python的map()传递bytes类型而非int类型?
问题:如何让map()处理bytes对象时传递bytes类型而非整数?
我有一个bytestring,想要处理其中的每个bytes。本来想用map()来实现,但直接遍历bytestring时,索引访问会把单个字节转换成整数(这个行为没法直接阻止),导致map()传递给函数的是整数而不是bytes类型。
示例代码:
def test_function(input): print(type(input)) before = b'\x00\x10\x00\x00\x07\x80\x00\x03' print("After with map") after_with_map = list(map(test_function, before[:])) print("After without map") for i in range(len(before)): test_function(before[i:i+1])
使用map()后的输出:
<class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'> <class 'int'>
不使用map()的输出:
<class 'bytes'> <class 'bytes'> <class 'bytes'> <class 'bytes'> <class 'bytes'> <class 'bytes'> <class 'bytes'> <class 'bytes'>
请问有没有办法强制map()传递bytes类型而非整数类型?
解决方法
方法一:生成单个字节的bytes切片序列
通过生成器表达式把原bytestring拆成单个字节的切片,这样map()遍历的就是bytes类型对象:
after_with_map = list(map(test_function, (before[i:i+1] for i in range(len(before)))))
方法二:在处理函数中将整数转回bytes
如果不想修改遍历的序列,可以在函数内部把传入的整数转换为bytes类型:
def test_function(input): if isinstance(input, int): input = bytes([input]) print(type(input)) after_with_map = list(map(test_function, before[:]))
方法三:自定义生成器遍历单个字节切片
对于长bytestring,自定义生成器可以更高效地生成单个字节的切片:
def single_byte_generator(b): for i in range(len(b)): yield b[i:i+1] after_with_map = list(map(test_function, single_byte_generator(before)))
内容的提问来源于stack exchange,提问作者LLL
相关产品推荐
相关产品推荐

