How can I convert a tuple to a float in python?

怎甘沉沦 提交于 2019-12-24 14:34:38

问题


Say I created a tuple like this using a byte array:

import struct
a = struct.unpack('f', 'helo')

How can I now convert a into a float? Any ideas?


回答1:


struct.unpack always returns a tuple, because you can unpack multiple values, not just one.

A tuple is a sequence, just like a list, or any other kind of sequence. So, you can index it:

>>> a = struct.unpack('f', 'helo')
>>> b = a[0]
>>> b
7.316105495173273e+28

… or use assignment unpacking:

>>> b, = a
>>> b
7.316105495173273e+28

… or loop over it:

>>> for b in a:
...     print(b)
7.316105495173273e+28

And of course you can combine any of those into a single line:

>>> b = struct.unpack('f', 'helo')[0]
>>> b, = struct.unpack('f', 'helo')
>>> c = [b*b for b in struct.unpack('f', 'helo')]

If this isn't obvious to you, you should read Lists, More on Lists, and Tuples and Sequences in the tutorial.




回答2:


You probably could do this:

a = a[0]



来源:https://stackoverflow.com/questions/20483239/how-can-i-convert-a-tuple-to-a-float-in-python

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