在Python中locals()['_ [1]']是什么意思?
问题内容:
我看到了一个衬里代码,该代码声称可以删除序列中的重复项:
u = [x for x in seq if x not in locals()['_[1]']]
我在ipython(使用python 2.7)中尝试了该代码, KeyError: '_[1]'
['_[1]']
在Python中是否有特殊之处?
问题答案:
locals()['_[1]']
是一种访问列表理解内的列表理解(或生成器)当前结果的引用的方法。
这是很邪恶的,但是会产生有趣的结果:
>> [list(locals()['_[1]']) for x in range(3)]
[[], [[]], [[], [[]]]]
在此处查看更多详细信息:the-secret-name-of-list-
comprehensions
。