如何在Python中将元组转换为浮点数? [英] How can I convert a tuple to a float in python?

查看:1027
本文介绍了如何在Python中将元组转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我使用字节数组创建了这样的元组:

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

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

我现在如何将a转换为浮点数?有什么想法吗?

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

推荐答案

struct.unpack总是返回一个元组,因为您可以解压缩多个值,而不仅仅是一个值.

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

…或使用作业拆箱:

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

…或在其上循环:

>>> 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.

这篇关于如何在Python中将元组转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆