简体   繁体   English

CSV字符串到python列表中的小数

[英]CSV string to decimal in python list

I am using an API that returns what appears to be a CSV string that i need to parse for two decimal numbers and then need to append those numbers to separate lists as decimal numbers (also while ignoring the timestamp at the end): 我正在使用一个API,该API返回似乎是CSV字符串的字符串,我需要解析该字符串以获取两个十进制数字,然后需要将这些数字作为十进制数字附加到单独的列表中(同时忽略结尾处的时间戳):

returned_string_from_API = '0,F,F,1.139520,1.139720,0,0,20160608163132000'
decimal_lowest_in_string = []
decimal_highest_in_string = []

Processing time is a factor in this situation so, what is the fastest way to accomplish this? 在这种情况下,处理时间是一个因素,那么,最快的方法是什么?

Split the string by comma: 用逗号分割字符串:

>>> string_values = returned_string_from_API.split(',')
>>> string_values
['0', 'F', 'F', '1.139520', '1.139720', '0', '0', '20160608163132000']

Get the values from string: 从字符串获取值:

>>> string_values[3:5]
['1.139520', '1.139720']

Convert to float : 转换为float

>>> decimal_values = [float(val) for val in string_values[3:5]]
>>> decimal_values
[1.13952, 1.13972]

Get min and max in the appropriate list: 在适当的列表中获取最小值和最大值:

>>> decimal_lowest_in_string = []
>>> decimal_highest_in_string = []
>>> decimal_lowest_in_string.append(min(decimal_values))
>>> decimal_lowest_in_string
[1.13952]
>>> decimal_highest_in_string.append(max(decimal_values))
>>> decimal_highest_in_string
[1.13972]

Fastest way is to use regular expression. 最快的方法是使用正则表达式。 Readability is another issue.. 可读性是另一个问题。

import re

returned_string_from_API = '0,F,F,1.139520,1.139720,0,0,20160608163132000'
decimal_lowest_in_string = []
decimal_highest_in_string = []

re_check = re.compile(r"[0-9]+\.\d*")
m = re_check.findall(returned_string_from_API)

decimal_lowest_in_string.append(min(m))
decimal_highest_in_string.append(max(m))

1) The version which does not rely on cvs 1)不依赖cvs的版本

returned_string_from_API = '0,F,F,1.139520,1.139720,0,0,20160608163132000'

def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False

float_numbers = filter(isfloat, returned_string_from_API.split(','))

2) try pandas package 2)尝试熊猫包

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

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