我在使用我正在迭代的函数中创建的列表时遇到问题。我的代码目前看起来像这样:
def get_things(i):
html=str(site[i])
browser = webdriver.Chrome() # Optional argument, if not specified will search path.
browser.get(html);
playerlist=[]
teamlist=[]
all_players = browser.find_elements_by_xpath("//a[@class='name']")
all_teams = browser.find_elements_by_xpath("//td[@class='last']")
for a in all_players:
playerlist.append(str(a.text))
print playerlist
for td in all_teams:
teamlist.append(str(td.text))
print teamlist
browser.quit()
return playerlist, teamlist
然后我想在我的程序中稍后在另一个函数中使用teamlist和playerlist。
for i in xrange(0,2):
get_things(i)
print teamlist #This is where Im told teamlist doesn't exist
print playerlist #This is where I'm told playerlist doesn't exist
print_sheet(teamlist, playerlist)
这两个打印报表对我来说是确保程序正在拾取项目。不过,我的问题是我被告知团队列表和玩家列表不存在。
NameError: name 'teamlist' is not defined
我相信return语句应该使这些可用于程序的其余部分,但事实并非如此。
如何将这些列表提供给程序的其余部分?
答案 0 :(得分:1)
使用以下
(teamlist, playerlist)=get_things(I)
当你的功能返回时,你需要处理它。
实施例
def add(a,b):
return a+b
n=add(6,8)
print n #n is 14
答案 1 :(得分:0)
您需要将返回值分配给get_things
到某些变量
for i in xrange(0,2):
playerlist , teamlist = get_things(i) # missing this
print teamlist #This is where Im told teamlist doesn't exist
print playerlist #This is where I'm told playerlist doesn't exist
print_sheet(teamlist, playerlist)