简体   繁体   English

将套接字接收的字节转换为Python 3中的float

[英]Convert bytes received by socket to float in Python 3

I've tried following the suggested answer here but did not get the intended result: Python Socket Received ASCII convert to actual numbers (float) 我尝试按照此处建议的答案进行操作,但未获得预期的结果: Python套接字收到的ASCII转换为实际数字(浮点数)

I'm receiving data in bytes format like so, using socket.recv(): 我正在使用socket.recv()接收字节格式的数据:

      b'(1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)'

I'm trying to receive the values above as a list of 30 floats. 我正在尝试接收上述值作为30个浮点数的列表。

I understand we have to use the struct library but I'm facing difficulties trying to grasp the concept of formatting. 我知道我们必须使用struct库,但是在尝试掌握格式概念时遇到了困难。

Your incoming floats aren't fixed-length, apart from having 6 decimal paces, if at all. 除了有6个小数步长之外,传入的浮点数不是固定长度的。 So why not just use bytes.decode() , then strip off the brackets and then split on commas? 那么,为什么不只使用bytes.decode() ,然后bytes.decode()括号,然后以逗号分隔呢?

With each step broken down: 每个步骤都需要分解:

>>> b = b'(1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)'
>>> b.decode()
'(1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)'
>>> b.decode()[1:-1]
'1,3,-121.551552,-123.602531,-40.582172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'
>>> b.decode()[1:-1].split(',')
['1', '3', '-121.551552', '-123.602531', '-40.582172', '0', '0', '0', '0', '0', '0', '0',
 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
>>> [float(x) for x in b.decode()[1:-1].split(',')]
[1.0, 3.0, -121.551552, -123.602531, -40.582172, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
 0.0, 0.0, 0.0, 0.0]

And a more Pythonic way to do that last one-step: 最后一步的一种更Python化的方法:

>>> list(map(float, b.decode()[1:-1].split(',')))
[1.0, 3.0, -121.551552, -123.602531, -40.582172, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM