[英]How to get all elements of an iterator using slice() built-in function in python without using the iterator's length?
If I have the following list: my_list = [1, 2, 3]
.如果我有以下列表:
my_list = [1, 2, 3]
。 How can I take all the elements using slice()
built-in method without knowing the length of my_list
?如何在不知道
my_list
长度的情况下使用slice()
内置方法获取所有元素?
my_list[slice(-1)]
gives me [1, 2]
and my_list[slice(':')]
gives me a TypeError. my_list[slice(-1)]
给我[1, 2]
和my_list[slice(':')]
给我一个 TypeError。
Is there something similar to my_list[:]
that I can use with slice so that I can define a variable before the list is created?是否有类似于
my_list[:]
的东西可以与 slice 一起使用,以便在创建列表之前定义变量?
You can pass None
你可以通过
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
I believe that my_list[:]
is just a syntactic sugar.我相信
my_list[:]
只是一个语法糖。 You can confirm this by dis
module.您可以通过
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.