How Can I Convert A Tuple To A Float In Python?
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?
Solution 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.
Solution 2:
You probably could do this:
a = a[0]
Post a Comment for "How Can I Convert A Tuple To A Float In Python?"