我从代码中收到以下错误:
File "D:/beverages.py", line XX, in <module>
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
ValueError: could not convert string to float: '-'
代码如下:
import math
class Residents :
def __init__(self,x,y,drink):
self._xco = x
self._yco = y
self._drink = drink
def drink(self):
return self._drink
def distance(self,other):
z = math.sqrt((float(self._xco) - float(other._xco))**2 + (float(self._yco) - float(other._yco))**2)
return z
def close(self,other):
if self.distance(other) < 1:
return True
return False
with open("surveydata.txt") as file :
file1 = file.readline()
relst = []
for line in file1 :
value = line.split()
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
x = input("Input a x-coordinate : ")
y = input("Input a y-coordinate : ")
defau = Residents(x,y,drink = "unknown")
sumcoke = 0
sumpepsi = 0
for res in relst :
if res.close(defau):
if res.drink() == "Coke" :
sumcoke += 1
elif res.drink() == "Pepsi":
sumpepsi += 1
pass
print("Number of Coke drinkers are : {0}". format(sumcoke) )
print("Number of Pepsi drinkers are : {0}". format(sumpepsi) )
surveydata.txt
文件包含:
-3.043296714578294 -1.8118219429417417 Pepsi
-2.934406412013738 -3.2258867426312845 Pepsi
3.750989559940674 0.6649706751908528 Coke
4.453731061614226 1.1760692786505302 Coke
-3.3141673450571307 2.7471154522861942 Coke
-1.5611978286453065 0.9748847584776836 Coke
-0.6446977323819532 -1.4945077535804119 Pepsi
-4.280039869935868 3.2099331922984433 Coke
我不知道为什么错误会抱怨单个-
字符,不是应该处理整个字段(带有符号和的数字)吗?
答案 0 :(得分:3)
您的问题就在这里
with open("surveydata.txt") as file:
file1 = file.readline() # <-- read ONE line
relst = []
for line in file1 :
value = line.split()
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
file1
变量仅包含文件的一行(作为字符串),而不包含每一行(作为字符串的集合)。这意味着for line in file1
将遍历字符串中的每个 character 而不是集合中的每个 line ,这就是为什么它抱怨单个,单独的{{ 1}}个字符。
因此,您应该将-
更改为file1 = file.readline()
以读取所有行:
file1 = file.readlines()
此外,尤其是对于较大的文件,遍历文件本身比使用with open("surveydata.txt") as file:
file1 = file.readlines()
relst = []
for line in file1:
value = line.split()
relst.append(Residents(float(value[0]),float(value[1]),str(value[2])))
效率更高,因为您不会将整个文件加载到内存中。因此,最终代码应如下所示:
.readlines()