Python列表理解流控制

时间:2018-10-04 18:13:08

标签: python list-comprehension control-flow

任何人都可以帮助我获得在函数内运行的列表理解吗,它是从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 个答案:

答案 0 :(得分:0)

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

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

“国家/城市”被附加两次,这与我运行了input()方法多少次有关,即使在引发异常时仍会执行以下代码:

尝试:
        placeList.append(p.group(0))