问题
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