2012-03-09 90 views

回答

9

locals()['_[1]']是在列表理解中访问对列表理解(或生成器)当前结果的引用的方式。

这是很邪恶,但能产生有趣的结果:

>> [list(locals()['_[1]']) for x in range(3)] 
[[], [[]], [[], [[]]]] 

在这里看到更多的细节:the-secret-name-of-list-comprehensions

+9

它不仅是一个邪恶的实现细节,它是在Python 2.7版删除的信息。不要使用它。 – Duncan 2012-03-09 10:06:18

1

locals()从Python文档:

更新,并返回来表示当前本地符号表的字典。在函数块中调用时,由locals()返回自由变量,但不在类块中调用。

我看不出为什么locals()用于那一个班轮,也许它不像你想要的一般。

如果你想从列表中删除重复我认为最好的选择是将其转换为一个set:如果您想再次名单

In [2]: l = [1,1,3,4,2,4,6] 
In [4]: set(l) 
Out[4]: set([1, 2, 3, 4, 6]) 

In [5]: list(set(l)) 
Out[5]: [1, 2, 3, 4, 6] 
7

它是Python 2.6及更早版本在列表理解中使用的临时名称。 Python 2.7和Python 3.x解决了这个问题:在创建完成之后,创建的列表将不再可用。

简而言之,这是一个没有人应该依赖的实现细节。

在这里你可以看到,Python 2.7版叶locals()不变,而Python 2.6创建一个短现场临时:

Python 2.7.2 (default, Jan 5 2012, 16:24:09) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> def foo(): 
     t = [list(locals().keys()) for x in range(1) ] 
     print(locals()) 
     print(t[0]) 

>>> foo() 
{'x': 0, 't': [['x']]} 
['x'] 
>>> 

Python 2.6.7 (r267:88850, Jan 5 2012, 16:18:48) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> def foo(): 
     t = [list(locals().keys()) for x in range(1) ] 
     print(locals()) 
     print(t[0]) 

>>> foo() 
{'x': 0, 't': [['_[1]', 'x']]} 
['_[1]', 'x'] 
>>> 

的Python 3.x中引入了一个新的短命的临时列表推导称为.0。不要试图将它用于任何事情。此外整个列表理解运行在一个单独的命名空间,因此循环变量无法在循环外访问:

Python 3.2 (r32:88445, Jan 5 2012, 16:29:57) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> def foo(): 
     t = [list(locals().keys()) for x in range(1) ] 
     print(locals()) 
     print(t[0]) 

>>> foo() 
{'t': [['.0', 'x']]} 
['.0', 'x'] 
3

哇!这是非常神秘的代码。花了一些研究来找到答案。

基本上列表理解是建立一个新的列表。它命名这个临时名单_[1]locals()部分仅使用locals()字典来查找该名称,因为否则无法访问该名称。这条线说...

[x for x in seq if x not in this_list] 

神秘。

的发现这个here