問題描述
在我看來,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 而不是普通的列表切片?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!