python - 如何将列表字符串转换为浮点数
问题描述
我正在使用 Python 乌龟来绘制飓风 Irma 的路径。在阅读文件并获得有用的数据(纬度、经度和风速)后,我收到了关于代码的映射部分如何无法接受字符串的错误。但是当我尝试将列表值转换为浮点数时,它给了我ValueError:无法将字符串转换为浮点数:'。'。我尝试使用 .split,但随后出现错误:没有足够的值来解包。
#open the file and extract the data
with open("irma.csv", 'rt') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
latitude = row["Lat"]
longitude = row["Lon"]
windspeed = row["Wind"]
#convert to float
latitude = [float(i) for i in latitude]
longitude = [float(i) for i in longitude]
#mapping the data to the Python turtle function
for lat, lon in latitude, longitude:
t.setpos(lat, lon)
for index in windspeed:
if index < 74:
t.pencolor("White")
t.width(2)
elif 74 <= index <= 95:
t.pencolor("Blue")
t.width(4)
elif 96 <= index <= 110:
t.pencolor("Green")
t.width(6)
elif 111 <= index <= 129:
t.pencolor("Yellow")
t.width(8)
elif 130 <= index <= 156:
t.pencolor("Orange")
t.width(10)
elif windspeed >= 157:
t.pencolor("Red")
t.width(12)
解决方案
这一行:
latitude = [float(i) for i in latitude]
正在遍历您纬度中的每个字符,包括“。” 不能转换为浮点数。经度也有同样的问题。
您在这里不需要列表理解。简单地:
latitude = float(latitude)
除非纬度和经度对象包含其他字符,否则应该是您要查找的内容。
不过,这似乎不是您唯一的问题。您的for row in reader
循环每次通过都会覆盖纬度和经度。
考虑到这一点,考虑使用更像这样的东西:
with open("irma.csv", 'rt') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
lat = float(row["Lat"])
lon = float(row["Lon"])
windspeed = row["Wind"]
t.setpos(lat, lon)
for index in windspeed:
if index < 74:
t.pencolor("White")
t.width(2)
elif 74 <= index <= 95:
t.pencolor("Blue")
t.width(4)
elif 96 <= index <= 110:
t.pencolor("Green")
t.width(6)
elif 111 <= index <= 129:
t.pencolor("Yellow")
t.width(8)
elif 130 <= index <= 156:
t.pencolor("Orange")
t.width(10)
elif windspeed >= 157:
t.pencolor("Red")
t.width(12)
推荐阅读
- kubernetes - Kubernetes + calico + 副本集
- javascript - 如何被点击 li 高亮显示
- javascript - MomentJS diff 增加了一个小时
- reactjs - 在反应js中调整谷歌地图框的大小
- java - 如何通过 sdkman 非交互式安装最新的 java 版本?
- python - 将相似的索引值分组并通过新索引 pandas 重新索引每个组
- asp.net-mvc - Asp.net Mvc 和 Boostrap 4 分页 - 显示活动的当前页面
- c# - 'public / static' 修饰符对此项无效
- java - 解析来自 REST 的压缩 InputStream
- ubuntu - 在 WSL 中完全删除 anaconda