将字符串矩阵从Arduino转换为Python中的浮点数

时间:2017-05-20 11:11:12

标签: python string numbers

我有一个Arduino,给我以下的值 我可以在Python中读取这个字符串矩阵,但我需要将这个值转换为浮点矩阵。

['-0.4152832031\t0.1403808593\t-0.1831054687\t-1.0670732259\t-0.0609756088\t0.0000000000\t185\t-1\t-683\r\n']
['-0.4165039062\t0.1406250000\t-0.1867675781\t-0.8841463088\t0.1524390220\t-0.0304878044\t186\t-2\t-685\r\n']
['-0.4140625000\t0.1411132812\t-0.1843261718\t-0.8536585807\t0.4573170661\t-0.2743902444\t186\t-1\t-686\r\n']
['-0.4165039062\t0.1408691406\t-0.1870117187\t-1.0365853309\t0.0304878044\t-0.1219512224\t185\t-2\t-685\r\n']
['-0.4165039062\t0.1389160156\t-0.1857910156\t-1.0060975551\t0.0304878044\t0.0000000000\t183\t0\t-683\r\n']
['-0.4147949218\t0.1396484375\t-0.1862792968\t-0.9756097793\t0.0609756088\t0.0304878044\t184\t0\t-684\r\n']
['-0.4147949218\t0.1401367187\t-0.1872558593\t-1.0670732259\t0.1524390220\t-0.1219512224\t185\t-2\t-685\r\n']
['-0.4147949218\t0.1381835937\t-0.1862792968\t-0.9756097793\t0.0304878044\t-0.1829268360\t185\t0\t-683\r\n']
['-0.4135742187\t0.1391601562\t-0.1887207031\t-0.9756097793\t0.1219512224\t-0.1219512224\t184\t-1\t-684\r\n']
['-0.4160156250\t0.1394042968\t-0.1848144531\t-0.9146341323\t-0.0304878044\t0.0000000000\t184\t-2\t-685\r\n']
['-0.4167480468\t0.1384277343\t-0.1855468750\t-1.0975609970\t0.0304878044\t0.0914634132\t183\t-2\t-686\r\n']
['-0.4155273437\t0.1381835937\t-0.1860351562\t-0.8841463088\t0.0000000000\t-0.1524390220\t184\t-4\t-685\r\n']
['-0.4162597656\t0.1396484375\t-0.1845703125\t-0.9451219558\t0.1524390220\t-0.1524390220\t186\t-1\t-686\r\n']
['-0.4167480468\t0.1406250000\t-0.1870117187\t-1.0975609970\t0.0000000000\t0.0304878044\t184\t-2\t-684\r\n']
['-0.4162597656\t0.1369628906\t-0.1838378906\t-1.0060975551\t-0.0914634132\t-0.0304878044\t185\t-2\t-684\r\n']
['-0.4155273437\t0.1384277343\t-0.1865234375\t-1.4634146690\t0.0000000000\t0.1219512224\t185\t-1\t-683\r\n']

1 个答案:

答案 0 :(得分:1)

为了将您的字符串转换为float个数字列表,您可以将列表理解表达式与str.split()一起使用,并将每个值类型转换为{{3 as:

>>> num_str = '-0.4152832031\t0.1403808593\t-0.1831054687\t-1.0670732259\t-0.0609756088\t0.0000000000\t185\t-1\t-683\r\n'

>>> [float(n) for n in num_str.split()]
[-0.4152832031, 0.1403808593, -0.1831054687, -1.0670732259, -0.0609756088, 0.0, 185.0, -1.0, -683.0]

或者,您可以使用float获得与以下相同的结果:

>>> map(float, num_str.split())
[-0.4152832031, 0.1403808593, -0.1831054687, -1.0670732259, -0.0609756088, 0.0, 185.0, -1.0, -683.0]

注意: map()在Python 3.x中返回生成器对象。要将其转换为列表,您必须使用list

明确地将值转换为list(map(..., ...))