为什么 Python 数组模块处理字符串和列表的方式不同?
我无法理解以下语句的结果:
>>> from array import array
>>> array('L',[0xff,0xff,0xff,0xff])
array('L', [255L, 255L, 255L, 255L])
>>> from array import array
>>> array('L','\xff\xff\xff\xff')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: string length not a multiple of item size
I'm having trouble understanding the result of the following statements:
>>> from array import array
>>> array('L',[0xff,0xff,0xff,0xff])
array('L', [255L, 255L, 255L, 255L])
>>> from array import array
>>> array('L','\xff\xff\xff\xff')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: string length not a multiple of item size
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在 64 位 Python 版本上运行此程序,其中
array
将类型代码'L'
视为 64 位无符号整数。文档不是很清楚。它只说明
'L'
至少是四个字节。You are running this on a 64-bit build of Python, on which
array
treats type code'L'
as a 64-bit unsigned integer.The documentation isn't very clear. All it says is that
'L'
is at least four bytes.在第一种情况下,您将从包含 4 个元素的列表中初始化数组。这将为您提供一个包含 4 个元素的数组:列表中的每个值对应一个元素。
在第二种情况下,您从字节字符串初始化数组:字符串中的字节将直接复制到数组中。 “L”说明符创建一个无符号长整型数组,其最小大小为 4 字节。
在我的机器(Windows 64 位 Python 2.6)上,从 4 字节字符串初始化工作正常:
我猜您使用的任何版本的 Python 都有 8 字节而不是 4 字节的无符号长整型。尝试将您从列表创建的数组转换回一个字符串并查看包含多少个字节:
PS 我假设您使用的是 Python 2.x,在 Python 3.x 上您会得到 TypeError。
In the first case you are initializing the array from a list with 4 elements. That will give you an array with 4 elements: one for each value in the list.
In the second case you are initializing the array from a byte string: the bytes in the string will be copied directly into the array. The 'L' specifier creates an array of unsigned longs which have a minimum size of 4 bytes.
On my machine (Windows 64 bit Python 2.6) initializing from a 4 byte string works fine:
I guess whichever version of Python you are using has unsigned longs that are 8 bytes rather than 4. Try converting the array you created from a list back to a string and see how many bytes that contains:
P.S. I'm assuming that you are using Python 2.x, on Python 3.x you would have got a TypeError instead.