Python - 变量类型给出不同的答案

时间:2016-01-18 04:07:08

标签: python python-2.7 types

我正在阅读二进制文件,这是我在byte1byte2中表示的两个字节 byte是一个列表

byte1 = byte[i]
byte2 = byte[i+1]
value1 = struct.unpack('B',byte1)[0], #this will be integer
value2 = struct.unpack('B',byte2)[0]
print type(value1) 
print type(value2)

但是当我看到输出时,value1和value2都给出了不同的类型,而应该显示相同的。

输出:

<type 'tuple'>
<type 'int'>

我错过了什么?

谢谢。

1 个答案:

答案 0 :(得分:4)

行尾有逗号:

value1 = struct.unpack('B', byte1)[0], #this will be integer
#                                    ^

逗号将右侧变为元组。考虑:

>>> a = 1,
>>> type(a)
<type 'tuple'>
>>> a = 'foo',
>>> type(a)
<type 'tuple'>

在每种情况下,由于尾随逗号,表达式的计算结果为tuple。您发布的代码段也是如此。

要获得一个整数,只需删除逗号即可:

value1 = struct.unpack('B', byte1)[0]