我不明白为什么我的代码中出现此错误。" UnboundLocalError:局部变量' state'在分配之前引用" 我的理解是变量" state"是一个局部变量,我没有在函数之外使用它。
def get_list_of_university_towns():
with open("university_towns.txt") as townfile:
unitowns=townfile.readlines()
town_list=[]
for line in unitowns:
line.rstrip()
if line[-6:]=="[edit]":
state = line[:-6]
elif ' (' in line:
town = line[:line.index("(")-1]
town_list.append([state,town])
else:
town = line
town_list.append([state,town])
unitown_pd=pd.DataFrame(town_list, columns=["State","RegionName"])
return unitown_pd
get_list_of_university_towns()
答案 0 :(得分:0)
我找到了答案。我需要在if中添加一个“continue”。
def get_list_of_university_towns():
import pandas as pd
with open("university_towns.txt") as townfile:
unitowns=townfile.readlines()
#print(unitowns)
town_list=[]
for line in unitowns:
line=line.rstrip()
if line[-6:]=="[edit]":
state = line[:-6]
#print(state)
continue
elif ' (' in line:
town = line[:line.index("(")-1]
town_list.append([state,town])
else:
town = line
town_list.append([state,town])
unitown_pd=pd.DataFrame(town_list, columns=["State","RegionName"])
return unitown_pd.head()