Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python eval忽略本地,寻找全局_Python_Global Variables_Eval_Local Variables - Fatal编程技术网

python eval忽略本地,寻找全局

python eval忽略本地,寻找全局,python,global-variables,eval,local-variables,Python,Global Variables,Eval,Local Variables,在新的Python 3.4.1 shell窗口中运行此代码时: >>> def golf(c): a,d=[],{"U":"a.append(int(x[5]))","O":'a.pop() if a else 0',"E":'a[-1]'} return sum(eval(d[x[1]])or 0 for x in c)or 0 >>> golf(("PUSH 3", "POP", "POP", "PUSH 4", "PEEK", "PUSH 9",

在新的Python 3.4.1 shell窗口中运行此代码时:

>>> def golf(c):
 a,d=[],{"U":"a.append(int(x[5]))","O":'a.pop() if a else 0',"E":'a[-1]'}
 return sum(eval(d[x[1]])or 0 for x in c)or 0

>>> golf(("PUSH 3", "POP", "POP", "PUSH 4", "PEEK", "PUSH 9", "PUSH 0", "PEEK", "POP", "PUSH 1", "PEEK"))
即使我在第二行中声明了a,也会出现这个错误--a,d=[],{

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    golf(("PUSH 3", "POP", "POP", "PUSH 4", "PEEK", "PUSH 9", "PUSH 0", "PEEK", "POP", "PUSH 1", "PEEK"))
  File "<pyshell#24>", line 3, in golf
    return sum(eval(d[x[1]])or 0 for x in c)or 0
  File "<pyshell#24>", line 3, in <genexpr>
    return sum(eval(d[x[1]])or 0 for x in c)or 0
  File "<string>", line 1, in <module>
NameError: name 'a' is not defined
即使a仍然未定义(在shell窗口中),我得到:

为什么eval()忽略我的本地a

使用Python习惯用法:

使用Python惯用语:

def golf(c):
 a,d=[],{"U":"a.append(int(x[5]))","O":'a.pop() if a else 0',"E":'a[-1]'}
 for x in c:
  print(eval(d[x[1]])or 0)
 return []
0
3
0
0
4
0
0
0
0
0
1
[]
def good_append(new_item, a_list=None):
    if a_list is None:
        a_list = []
    a_list.append(new_item)
    return a_list