如何在不使用迭代器长度的情况下使用 python 中的 slice() 内置函数获取迭代器的所有元素?

How to get all elements of an iterator using slice() built-in function in python without using the iterator's length?

如果我有以下列表:my_list = [1, 2, 3]。如何在不知道 my_list 长度的情况下使用 slice() 内置方法获取所有元素?

my_list[slice(-1)] 给我 [1, 2]my_list[slice(':')] 给我一个类型错误。

是否有类似于 my_list[:] 的东西可以与 slice 一起使用,以便我可以在创建列表之前定义变量?

你可以通过None

>>> my_list = [1, 2, 3]
>>> id(my_list)
1827682884416
>>> copy = my_list[slice(None)]
>>> id(copy)
1827682861888
>>> copy
[1, 2, 3]
>>> my_list is copy
False

我认为my_list[:]只是一个语法糖。您可以通过 dis 模块确认这一点。

>>> import dis
>>> dis.dis("my_list[:]")
  1           0 LOAD_NAME                0 (my_list)
              2 LOAD_CONST               0 (None)
              4 LOAD_CONST               0 (None)
              6 BUILD_SLICE              2
              8 BINARY_SUBSCR
             10 RETURN_VALUE

如您所见,[:] 语法被编译为 None 并且是 used to build the slice later.