2017-10-17 37 views
0

我有一个字符串 - 数据从* .TXT读在转换剥离串之间的空间,列出

21 197 251 251 253 107 0 0 0 0 0 

要转换到列表如下:

[21.0, 197.0, 251.0, 251.0, 253.0, 107.0, 0, 0, 0, 0, 0] 

写了这个功能,试图选项#1,#2,和#3

def loadCsv(filename): 
    lines = csv.reader(open(filename, "rb")) 
    dataset = list(lines) 
    for i in range(len(dataset)): 
     #1 dataset[i] = [float(x) for x in dataset[i]] 
     #2 dataset[i] = [map(float, x.strip()) for x in dataset[i]] 
     #3 dataset[i]=[map(float, x.split()) for x in dataset[i]] 
    return datase 

当我使用:

  1. 字符串显然不能被转换为浮动,

Error I receive ValueError: invalid literal for float()

  • 我认为存在这样导致它的元素之间的空间。
  • ValueError: could not convert string to float: there is space that is causing that error

  • 当我映射串使用此浮动,它适用于这个功能,但然后当我所说的数据进行分类,它呈现
  • unhashable list error

    def separateByClass(dataset): 
        separated = {} 
        for i in range(len(dataset)): 
         vector = dataset[i] 
         if (vector[-1] not in separated): 
          separated[vector[-1]] = [] 
         separated[vector[-1]].append(vector) 
        return separated 
    

    有什么想法?


    I am updating loadCsv function as below which resolved the issue:


    def loadCsv(filename): 
        lines = open(filename) 
        lines=lines.read() 
        dataset = list(lines.split())#list(lines) 
    
        for i in range(len(dataset)): 
    
         #dataset[i] = [float(x) for x in dataset[i]] 
         #dataset[i]=[map(float, x.strip()) for x in dataset[i]] 
         dataset[i]=[float(x) for x in dataset[i]] 
        return dataset 
    
    +0

    都在同一行或单独行所有这些号码? –

    +0

    它的一个排出来多在txt文件 – lpt

    回答

    0

    dataset列表文件中的行的名单,但你的号码都在一个行,用空格隔开。您必须split该行,并将段转换为float

    你的最后一行[map(float, x.split()) for x in dataset[i]]接近,但如果dataset[i]是一条线,然后x是一个字符,即你迭代的行中的字符,分裂那些

    您可以使用map ...

    >>> line = "21 197 251 251 253 107 0 0 0 0 0" 
    >>> list(map(float, line.split())) 
    [21.0, 197.0, 251.0, 251.0, 253.0, 107.0, 0.0, 0.0, 0.0, 0.0, 0.0] 
    

    ...或列表理解:

    >>> [float(x) for x in line.split()] 
    [21.0, 197.0, 251.0, 251.0, 253.0, 107.0, 0.0, 0.0, 0.0, 0.0, 0.0] 
    

    从文件中读取(无需csv)结合这

    with open("data.txt") as f: 
        text = f.read() 
        data = list(map(float, text.split())) 
    

    不存在不可散列问题:结果是一个列表,它不能是请将set或(作为关键字)放入dict。为此,您必须将list转换为tuple

    +0

    感谢tobias_k的,实际上你的提示帮助。 – lpt

    0

    你可以使用splitlines()和列表理解:

    with open(filename, 'r') as f: 
         r = [float(item) for line in f.read().splitlines() for item in line.split(" ")] 
         print (r)