列表中的十进制错误

时间:2014-07-03 14:32:14

标签: python python-3.x

我试图输入一个可以用来进行计算的csv文件:

import csv
data=[]
file=input ("Enter file name: ")
with open(file,"r") as f:
      reader=csv.reader(f)

            for row in reader:
                  data.append([x.strip(";") for x in row])
            print(data)

print("Calculate COV")
lst= data
spl= [x.split(";") for y in lst for x in y]
flattened = [float(x) for y in spl for x in y if x]   
print (flattened)

但是当我使用十进制数字时,我会继续这样做:

  

[[' 13',' 25; 12',' 97; 13',' 12; 13',' ; 47; 13',' 44; 13',' 09; 12',' 86; 12',' 78; 12&#39 ;,' 91; 12',' 93; 12',' 91; 13',' 11'],[' 12',' 92; 13',' 42; 13',' 58; 13',' 7; 13',& #39; 62; 13',' 7; 13',' 31; 12',' 86; 12',' 59; 12& #39;,' 81; 13',' 46; 12',' 9'],[' 13',' 39; 13',' 5; 13',' 29; 13',' 26; 13',' 38; 13' ,' 45; 13',' 46; 11',' 95; 12; 12',' 57; 13',&#39 ; 22; 12',' 88'],[' 12',' 48; 13',' 76; 13', ' 7; 13',' 77; 13',' 08; 13',' 48; 13',' 25; 12',' 31; 12',' 56; 12',' 56; 12',' 95; 13',& #39; 38'],[' 12',' 52; 14',' 07; 14',' 46; 14&#39 ;,' 13; 13',' 98; 14',' 07; 13',' 92; 12',' 7; 13&#39 ;,' 01; 12',' 79; 13; 13',' 13']]

我什么时候应该这样:

  

[13.25,12.97,13.12,13.47,13.44,13.09,12.86,12.78,12.91,12.93,12.91,13.11,12.92,13.42,13.58,13.7,13.62,13.7,13.31,12.86,12.59,12.81,13.46, 12.9,13.39,13.5,13.29,13.26,13.38,13.45,13.46,11.95,12.57,13.22,12.88,12.48,13.76,13.7,13.77,13.08,13.48,13.25,12.31,12.56,12.56,12.95,13.38,12.52, 14.07,14.46,14.13,13.98,14.07,13.92,12.7,13.01,12.79,13.0,13.13]

2 个答案:

答案 0 :(得分:2)

您现在还不清楚如何使用CSV模块。首先,默认情况下,csv模块将使用逗号分隔值,而不是以分号分隔的值。

但无论如何,让我们尝试编写一些代码:

import csv

class MyDialect(csv.excel):
    delimiter = ';'

with open('in.csv', 'r') as f:
    reader = csv.reader(f, MyDialect())
    data = list(reader)

data = [[float(elem.replace(',', '.')) for elem in line] for line in data]

for line in data:
    print line

in.csv

13,25;12,97;13,12;13,47;13,44;13,09;12,86;12,78;12,91;12,93;12,91;13,11
12,92;13,42;13,58;13,7;13,62;13,7;13,31;12,86;12,59;12,81;13,46;12,9
13,39;13,5;13,29;13,26;13,38;13,45;13,46;11,95;12;12,57;13,22;12,88
12,48;13,76;13,7;13,77;13,08;13,48;13,25;12,31;12,56;12,56;12,95;13,38
12,52;14,07;14,46;14,13;13,98;14,07;13,92;12,7;13,01;12,79;13;13,13

标准输出

[13.25, 12.97, 13.12, 13.47, 13.44, 13.09, 12.86, 12.78, 12.91, 12.93, 12.91, 13.11]
[12.92, 13.42, 13.58, 13.7, 13.62, 13.7, 13.31, 12.86, 12.59, 12.81, 13.46, 12.9]
[13.39, 13.5, 13.29, 13.26, 13.38, 13.45, 13.46, 11.95, 12.0, 12.57, 13.22, 12.88]
[12.48, 13.76, 13.7, 13.77, 13.08, 13.48, 13.25, 12.31, 12.56, 12.56, 12.95, 13.38]
[12.52, 14.07, 14.46, 14.13, 13.98, 14.07, 13.92, 12.7, 13.01, 12.79, 13.0, 13.13]

答案 1 :(得分:1)

试试这个:

import csv
data=[]
import re
with open("out.csv","r") as f:
        reader=csv.reader(f,delimiter=";")
        for row in reader:
              print row
              data+=[x.split(",") for x in row]
        print(data)

print("Calculate COV")

flattened = [float(x) for y in data for x in y]