问题
we can simply use:
crc = struct.unpack('>i', data)
why people like this:
(crc,) = struct.unpack('>i', data)
what does the comma mean?
回答1:
The first variant returns a single-element tuple:
In [13]: crc = struct.unpack('>i', '0000')
In [14]: crc
Out[14]: (808464432,)
To get to the value, you have to write crc[0]
.
The second variant unpacks the tuple, enabling you to write crc
instead of crc[0]
:
In [15]: (crc,) = struct.unpack('>i', '0000')
In [16]: crc
Out[16]: 808464432
回答2:
the unpack
method returns a tuple of values. With the syntax you describe one can directly load the first value of the tuple into the variable crc
while the first example has a reference to the whole tuple and you would have to access the first value by writing crc[1]
later in the script.
So basically if you only want to use one of the return values you can use this method to directly load it in one variable.
回答3:
The comma indicates crc
is part of a tuple. (Interestingly, it is the comma(s), not the parentheses, that indicate tuples in Python.) (crc,)
is a tuple with one element.
crc = struct.unpack('>i', data)
makes crc
a tuple.
(crc,) = struct.unpack('>i', data)
assigns crc
to the value of the first (and only) element in the tuple.
回答4:
(crc,)
is considered a one-tuple.
来源:https://stackoverflow.com/questions/13894350/what-does-the-comma-mean-in-pythons-unpack