gpt4 book ai didi

python - 如何在其 if 条件下解决列表理解的当前状态?

转载 作者:行者123 更新时间:2023-12-05 08:14:45 24 4
gpt4 key购买 nike

我想在下面的代码中对 L 中的项目进行循环:

L = [1,2,5,2,1,1,3,4]
L_unique = []
for item in L:
if item not in L_unique:
L_unique.append(item)

像这样的列表理解:

L_unique = [ item for item in L if item not in ???self??? ]

这在 Python 中可行吗?如果可能,如何实现?

最佳答案

List comprehension其实是做一个匿名函数然后调用它,但是构建出来的list并不会存入局部变量字典,而是保存在Python维护的栈中,所以很少有Python级别的操作可以得到这个list(gc是一个疯狂但可行的选择。抱歉我之前夸张了,最后附上使用gc的解决方案):

>>> [locals().copy() for i in range(3)]
[{'.0': <range_iterator at 0x207eeaca730>, 'i': 0}, # does not contain the built list
{'.0': <range_iterator at 0x207eeaca730>, 'i': 1},
{'.0': <range_iterator at 0x207eeaca730>, 'i': 2}]
>>> dis('[i for i in iterable]')
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x00000211FEAFD000, file "<dis>", line 1>)
2 LOAD_CONST 1 ('<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_NAME 0 (iterable)
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE

Disassembly of <code object <listcomp> at 0x00000211FEAFD000, file "<dis>", line 1>:
1 0 BUILD_LIST 0 # build an empty list and push it onto the stack
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 4 (to 14)
6 STORE_FAST 1 (i)
8 LOAD_FAST 1 (i)
10 LIST_APPEND 2 # get the built list through stack and index
12 JUMP_ABSOLUTE 2 (to 4)
>> 14 RETURN_VALUE

对于您提供的示例,您可以使用 list(dict.fromkeys(L)) 在 Python 3.7+ 中获得相同的结果。这里我使用 dict 而不是 set 因为 dict 可以保留插入顺序:

>>> list(dict.fromkeys(L))
[1, 2, 5, 3, 4]

根据@KellyBundy 的说法,目前我找到的方法是使用gc.get_objects,但是这个操作非常昂贵(因为它收集了超过 1000 个对象),我无法确定它准确性:

>>> [item for item in L if item not in gc.get_objects(0)[-1]]
[1, 2, 5, 3, 4]

通过缓存降低操作成本:

>>> lst = None
>>> [item for item in L if item not in (lst := gc.get_objects(0)[-1] if lst is None else lst)]
[1, 2, 5, 3, 4]

关于python - 如何在其 if 条件下解决列表理解的当前状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73753000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com