我正在从CSV文件中读取并创建了一个功能,将玩家与该文件分成2个列表:经验丰富且新鲜的玩家。
然后,我尝试创建另一个打印每个列表长度的函数。但是,当我运行我的脚本并调用2个函数时,Python会返回一个错误,指出第二个函数的变量未定义。不知道我做错了什么。
for row in range(0,len(shape.part() )):
print row
结果:
import csv
with open('soccer_players.csv', newline='') as csvfile:
players_reader = csv.DictReader(csvfile, delimiter=',')
players = list(players_reader)
def separate(players):
experienced = []
fresh = []
for player in players:
if player['Soccer Experience'] == 'YES':
experienced.append(player)
else:
fresh.append(player)
return experienced, fresh
def countexperience (experienced, fresh):
players_experience = len(experienced)
players_fresh = len(fresh)
print(players_experience)
print(players_fresh)
while True:
start = input("Want to start? (Y/n) ").lower()
if start == "y":
separate(players)
countexperience(experienced, fresh)
break
elif start == "n":
print("goodbye")
break
else:
print("letter not accepted! Please write 'Y' to start or 'N' to exit!\n")
答案 0 :(得分:0)
separate()
中的局部变量未添加到当前范围,因此您需要将separate()
的返回值分配给当前范围中的变量,例如:
experienced, fresh = separate(players)
注意:您可以使用任何您想要的名称,例如
e, f = separate(players)
countexperience(e, f)
您还可以使用tuple
将函数调用中separate()
的{{1}}返回值直接扩展为countexperience()
,例如:
*