简体   繁体   English

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

[英]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.

相关问题 内置函数 iter() 如何将 Python 列表转换为迭代器? - How does the built-in function iter() convert a Python list to an iterator? 如何创建内置函数计数,而无需使用它。 蟒蛇 - How to create the built-in function count, without using it. python 使用Python 2.7获取循环内(非无限)迭代器的长度 - Get length of a (non infinite) iterator inside it's loop using Python 2.7 在不使用python内置函数的情况下计算或添加列表元素 - Count or add list elements without using python built-in functions 在不使用Python内置的Sort的情况下对元组进行排序 - Sort Tuples without using Python's built-in Sort 在不使用内置 function 的情况下随机播放 python 列表 - Shuffle a python list without using the built-in function 在不使用 python 内置 function 和 if 条件的情况下,在列表中计数 5 - count 5 in the list without using python built-in function and if condition 如何获取 Python 迭代器的当前值 - 取消引用迭代器而不增加 - How to get the current value of a Python iterator - dereferencing an iterator without incrementing 如何在不使用内置排序功能的情况下,根据元素按字母顺序对2D数组排序? (蟒蛇) - How to alphabetically sort 2D array based on an element, without using the built-in sort function? (python) 如何从python中的给定数据中删除字符串(不使用任何内置函数)? - How to delete string from given data in python(without using any built-in function)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM