what does the comma mean in python's unpack?

半腔热情 提交于 2021-02-20 14:58:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!