为什么我要使用 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.
相关文章