0

So I am trying to run this piece of code:

reader = list(csv.reader(open('mynew.csv', 'rb'), delimiter='\t'))
print reader[1]
number = [float(s) for s in reader[1]]

inside reader[1] i have the following values:

'5/1/2013 21:39:00.230', '46.09', '24.76', '0.70', '0.53', '27.92',

I am trying to store each one of values into an array like so:

number[0] = 46.09
number[1] = 24.09
and so on.....

My question is: how would i skip the date and the number following it and just store legitimate floats. Or store the contents in an array that are separated by comma?

It throws an error when I try to run the code above:

ValueError: invalid literal for float(): 5/1/2013 21:39:00.230

Thanks!

4

4 回答 4

5

跳过不能转换为浮点数的值:

number = []
for s in reader[1]:
   try:
       number.append(float(s))
   except ValueError:
       pass
于 2013-05-16T07:07:21.983 回答
0

如果它始终是第一个不是浮点数的值,则可以将其取出:

reader = list(csv.reader(open('mynew.csv', 'rb'), delimiter='\t'))
print reader[1]
number = [float(s) for s in reader[1][1:]]
于 2013-05-16T07:08:38.927 回答
0

或者您可以在字符串中搜索 / 并传递(如果存在),类似这样

my_list_results = []
my_list = ['5/1/2013 21:39:00.230', '46.09', '24.76', '0.70', '0.53', '27.92']
for m in my_list:
    if '/' not in m: #if we don't find /
        my_list_results.append(m)
print my_list_results
于 2013-05-16T07:10:24.777 回答
0
number = []
for s in reader[1]:
   number.append(int(float(s)))

这会将字符串转换为精确的浮点数

于 2013-05-16T07:12:27.433 回答