Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

python - Why would I want to use itertools.islice instead of normal list slicing?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...