[英]invalid python syntax in my 'for' loop
def citypop():
import csv
F = open("Top5000Population.txt")
csvF = csv.reader(F)
D = {}
with csvF for row in csvF:
city,state,population = row[0],row[1],row[2]
population = population.replace(',','')
population = int(population)
city = city.upper()[:12]
D[(city, state)] = population
return D
函数citypop()
返回一个以(city,state)
为键,以该城市(在该州)的人口作为值的字典。
我不断收到语法错误..我不正确理解csv模块吗?
编辑:谢谢您的帮助。...这应该工作,但现在突然我得到了错误
for city, state, population in reader(F): File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors[0]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa4 in position 7062: ordinal not in range(128)
当我运行测试用例时..有什么建议吗?
当您尝试与statement一起使用时,您认为您的意思是这样-在这种情况下,文件将在其下保留代码后立即关闭:
from csv import reader
def citypop():
D = {}
with open("Top5000Population.txt") as F:
for city, state, population in reader(F):
city = city.upper()[:12]
D[(city, state)] = int(population.replace(',',''))
return D
要么:
def citypop():
with open("Top5000Population.txt") as F:
return dict(((x.upper()[:12], y), int(z.replace(',', '')) for x, y, z in reader(F))
我认为您误解了Python的with
语句 。 制作第6行:
for row in csvF:
应该解决问题。
作为参考, with
语句与C#中的using
语句基本相同; 它声明了完成后需要卸载或释放的资源范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.