为什么我要使用itertools.islice而不是正常的列表切片? [英] Why would I want to use itertools.islice instead of normal list slicing?

查看:157
本文介绍了为什么我要使用itertools.islice而不是正常的列表切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来, itertools 模块中的许多函数都有更简单的等价物。例如,据我所知, itertools.islice(范围(10),2,5)范围(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而不是正常的列表切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆