How can I convert a tuple to a float in python?
25,602
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.
Author by
user2426316
Updated on December 10, 2020Comments
-
user2426316 over 3 years
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? -
abarnert over 10 yearsIt's already a float; that's guaranteed by using the
'f'
format character instruct.unpack
. So callingfloat
doesn't do anything useful. -
abarnert over 10 yearsWell, yes, but
a = a[0]
also does it. You might as well writea = float(a[int(0)]
while you're at it.