Python:在列表理解本身中引用列表理解?

asp*_*pin 0 python list-comprehension list

这个想法刚刚出现在我的脑海中。假设您出于某种原因想要通过 Python 中的列表理解来获取列表的唯一元素。

[i if i in {created_comprehension} else 0 for i in [1, 2, 1, 2, 3]

[1, 2, 0, 0, 3]

我不知道,我确实没有这样做的目的,但如果可以在创建时引用理解,那就太酷了。

(例如,如何使用列表理解从列表中删除重复的项目?是一个类似的问题)

sup*_*ain 5

我假设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]
Run Code Online (Sandbox Code Playgroud)

这会在创建新列表之前获取垃圾回收跟踪的所有对象的 ID ,然后在创建新列表之后,我们通过搜索新跟踪的空列表来找到它。调用一下self就可以使用了。所以中间两行是通用配方。我也成功地将它用于这个问题,但在我发布之前它就被关闭了。

更好的版本:

>>> [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]
Run Code Online (Sandbox Code Playgroud)

使用了这些辅助函数:

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)
Run Code Online (Sandbox Code Playgroud)

  • 哇。这太……可怕了。以一种有趣的方式,但仍然令人恐惧。:-) (3认同)