我假设 i in {created_comprehension} 应该是 i not in {created_comprehension}。至少数据表明是这样的。
所以这是一个有趣的可怕滥用,我不相信它总是有效的。主要是为了证明“这是不可能的,因为它还没有被赋值”这个论点是错误的。虽然列表对象确实尚未分配,但它确实在构建时已经存在。
>>> import gc
>>> [i if i not in self else 0
for ids in [set(map(id, gc.get_objects()))]
for self in [next(o for o in gc.get_objects() if o == [] and id(o) not in ids)]
for i in [1, 2, 1, 2, 3]]
[1, 2, 0, 0, 3]
这会获取为垃圾收集跟踪的所有对象的 ID,在创建新列表之前,然后在创建新列表之后,我们通过搜索新列表来找到它跟踪的空列表。调用它self 然后你就可以使用它了。所以中间的两行是一个通用的配方。我也成功地将它用于this question,但在我发帖之前它就被关闭了。
更好的版本:
>>> [i if i not in self else 0
for old in [ids()] for self in [find(old)]
for i in [1, 2, 1, 2, 3]]
[1, 2, 0, 0, 3]
使用了这些辅助函数:
def ids():
import gc
return set(map(id, gc.get_objects()))
def find(old):
import gc
return next(o for o in gc.get_objects() if o == [] and id(o) not in old)