问题描述
任何人都可以帮助我获得在函数内部运行的列表理解吗,它是从REPL运行的。 我在while循环的内部和外部尝试了各种缩进和放置,代码将无错误运行,但是未定义/创建了“ newlist”对象。我正在使用此列表理解来拆分collect_places()的输入字符串。 我不明白为什么理解力不产生新的清单。
输入字符串
'uk, london'
清单理解
newlist = [str.split(',') for str in placeList]
这是代码
import sys
import re
placeList=[]
visits=[[],[]] # created for later use
def collect_places():
"""this function will collect country city pairs"""
while True:
placed = input('Enter a country and city separated by a comma: ')
if placed =="":
sys.exit()
p=re.search('.*\,.*', placed)
try:
placeList.append(p.group(0))
except AttributeError as atr:
print('Try again')
continue
newlist = [str.split(',') for str in placeList]
这是脚本和错误
collect_places()
Enter a country and city separated by a comma: uk,london
Enter a country and city separated by a comma: eh
Try again
Enter a country and city separated by a comma:
newlist
Traceback (most recent call last):
File “<pyshell#343>”, line 1, in
newlist
NameError: name ‘newlist’ is not defined
此操作已成功由REPL执行
placeList
[‘uk,london’]
newlist = [str.split(’,’) for str in placeList]
newlist
[[‘uk’, ‘london’]]
1楼
我意识到newlist没有定义为全局变量。
Local variables of functions can’t be accessed from outside when the function call has finished:
至于“国家/城市”被附加两次,则与我运行input()方法的次数有关,即使在引发异常时仍会执行以下代码:
尝试:
placeList.append(p.group(0))