Why would I want to use itertools.islice instead of normal list slicing?(为什么我要使用 itertools.islice 而不是普通的列表切片?)
问题描述
在我看来,itertools 模块中的许多函数都有更简单的等效项.例如,据我所知, itertools.islice(range(10),2,5) 与 range(10)[2:5] 和 itertools.chain([1,2,3],[4,5,6]) 和 [1,2,3]+[4,5,6]代码>.主文档页面提到了速度优势,但除此之外还有什么理由选择 itertools?
It seems to me that many functions in the itertools module have easier equivalents. For example, as far as I can tell, itertools.islice(range(10),2,5) does the same thing as range(10)[2:5], and itertools.chain([1,2,3],[4,5,6]) does the same thing as [1,2,3]+[4,5,6]. The main documentation page mentions speed advantages, but are there any reasons to choose itertools besides this?
推荐答案
解决你提出的两个例子:
To address the two examples you brought up:
import itertools
data1 = range(10)
# This creates a NEW list
data1[2:5]
# This creates an iterator that iterates over the EXISTING list
itertools.islice(data1, 2, 5)
data2 = [1, 2, 3]
data3 = [4, 5, 6]
# This creates a NEW list
data2 + data3
# This creates an iterator that iterates over the EXISTING lists
itertools.chain(data2, data3)
您想要使用迭代器而不是其他方法的原因有很多.如果列表非常大,则创建包含大型子列表的新列表可能会出现问题,或者特别是创建包含其他两个列表副本的列表.使用 islice() 或 chain() 允许您以您想要的方式迭代列表,而无需使用更多内存或计算来创建新的列表.此外,正如 unutbu 所述,您不能将括号切片或添加与迭代器一起使用.
There are many reasons why you'd want to use iterators instead of the other methods. If the lists are very large, it could be a problem to create a new list containing a large sub-list, or especially create a list that has a copy of two other lists. Using islice() or chain() allows you to iterate over the list(s) in the way you want, without having to use more memory or computation to create the new lists. Also, as unutbu mentioned, you can't use bracket slicing or addition with iterators.
我希望这是一个足够的答案;还有很多其他答案和其他资源可以解释为什么迭代器很棒,所以我不想在这里重复所有这些信息.
I hope that's enough of an answer; there are plenty of other answers and other resources explaining why iterators are awesome, so I don't want to repeat all of that information here.
这篇关于为什么我要使用 itertools.islice 而不是普通的列表切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我要使用 itertools.islice 而不是普通的列表
基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
