Python 列表理解流控制



谁能帮我得到一个列表理解来在函数内运行,它从 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’]]

我意识到newlist没有被定义为全局变量。

Local variables of functions can’t be accessed from outside when the function call has finished:

至于"国家,城市"被附加两次,这与我运行input((方法的次数有关,因为即使引发异常,以下代码仍然执行:

try:
placeList.append(p.group(0((

相关内容

  • 没有找到相关文章

最新更新