我有一个字符串 - 数据从* .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
当我使用:
- 字符串显然不能被转换为浮动,
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
都在同一行或单独行所有这些号码? –
它的一个排出来多在txt文件 – lpt