Python中的Iterable和Iterator

In python or in any other programming language, Iteration means to access each item of something one after another generally using a loop. For example if we have a list of car names and we want to print all the names one by one, we can do so using a for loop, like this:

在python或任何其他编程语言中, 迭代意味着通常使用循环来逐个访问某项的每一项。 例如,如果我们有一个汽车名称列表,并且想要一张一张地打印所有名称,则可以使用for循环这样做,如下所示:

# list of cars
cars = ['Audi', 'BMW', 'Jaguar', 'Kia', 'MG', 'Skoda']

for car in cars:
  print("Name of car: ", car)

Name of car: Audi Name of car: BMW Name of car: Jaguar Name of car: Kia Name of car: MG Name of car: Skoda

车名:奥迪车名:宝马车名:捷豹车名:起亚车名:MG车名:斯柯达

What we did in the code above was iteration which involved accessing all the items of the list one by one.

我们在上面的代码中所做的是迭代 ,该迭代涉及一个接一个地访问列表的所有项目。

什么是可迭代的? (What is an Iterable?)

In python programming, an iterable is anything that can be looped through or can be iterated over. For example, list, tuples, dictionaries, etc. all are iterables. In simpler words, anything that can appear on the right-side of a for-loop: for x in iterable: ... is an iterable.

在python编程中, 可迭代对象是可以循环或可以迭代的任何对象。 例如, listtuplesdictionaries等都是可迭代的。 用简单的话来说,任何可能出现在for循环右侧的内容: for x in iterable: ...中的for x in iterable: ...迭代的。

One important property of an iterable is that it has an __iter__() method or iter() method which allows any iterable to return an iterator object.

可迭代对象的一个​​重要属性是它具有__iter__()方法或iter()方法,该方法允许任何可迭代对象返回迭代器对象。

The iter() method internally makes a call to the __iter__() method and returns an iterator object.

iter()方法在内部调用__iter__()方法并返回迭代器对象。

什么是迭代器? (What is an Iterator?)

Iterator is an object which can be looped through and it maintains its state during the iteration which means it remembers where it is during an iteration.

迭代器是一个可以循环访问的对象,它在迭代过程中保持其状态,这意味着它可以记住迭代过程中的位置。

It has a __next__() method that returns the next value in the iteration and updates the state to point at the next value.

它具有__next__()方法,该方法返回迭代中的下一个值并更新状态以指向下一个值。

Iterators also have the __iter__() method that returns self object.

迭代器还具有返回self对象的__iter__()方法。

从Iterable获取Iterator对象 (Getting an Iterator object from Iterable)

We can easily get an iterator object by passing a predefined or pre-created iterable to the iter() method or by using the __iter__() method on that iterable.

我们可以通过将预定义或预先创建的iterable传递给iter()方法,或在该iterable上使用__iter__()方法,来轻松获得iterator对象。

For example:

例如:

演示地址

In the example above, we have used the iter() method, well we can try using the __iter__() method too, like this:

在上面的示例中,我们使用了iter()方法,也可以尝试使用__iter__()方法,如下所示:

# we can use __iter__() method too
cars_iter_new = cars.__iter__()

# print the data
print(cars_iter_new.__next__())

As you can see in the example above, the next() or the __next__() method increments the state of the corresponding iterator and returns the value that is next to the previous value.

如您在上面的示例中看到的那样, next()__next__()方法将递增相应迭代器的状态,并返回前一个值旁边的值。

Also, you must have noticed an exception in the output. The exceotion is the StopIteration exception which occurs when there are no values left in an iterator to iterate i.e. after the list has ended and we still try to call the next() or __next() method.

另外,您必须在输出中注意到异常。 例外是StopIteration异常,当迭代器中没有要迭代的值时(即列表结束后),并且我们仍然尝试调用next()__next()方法,就会发生这种异常。

这是for Loop在内部工作的方式吗? (Is this how for Loop works internally?)

Well yes! Rather than getting into all the trouble of getting the iterator object and then calling next function again and again, python provides us with loops like the for loop which internally performs all above steps.

嗯,是! python并没有为获取迭代器对象然后一次又一次地调用next函数带来麻烦,而是为我们提供了诸如for循环之类的循环,该循环在内部执行上述所有步骤。

So when we use a for loop like this:

因此,当我们使用这样的for循环时:

# list of cars
cars = ['Audi', 'BMW', 'Jaguar', 'Kia', 'MG', 'Skoda']

for car in cars:
  print("Name of car: ", car)

Internally, the for loop does this:

在内部, for循环执行此操作:

# iterator object is created
iter_obj = iter(cars)

while True:
	try:
		element = next(iter_obj)
		# perform some operation like print the value
	except StopIteration:
	    # break out of loop when the list ends 
		break

for loop in python is created to easily iterate over the iterables and now we know how it works internally using the iterator object.

在python中创建了for循环来轻松地迭代可迭代对象,现在我们知道了如何使用iterator对象在内部进行工作。

通过创建自定义迭代器使类可迭代 (Making a class Iterable by creating custom Iterator)

Now let's learn how to make our own iterators. It is super easy to make our own iterator, all we have to do is implement the methods __iter__() and __next().

现在让我们学习如何制作自己的迭代器。 制作自己的迭代器非常容易,我们要做的就是实现__iter__()__next()

The __iter__() method will return an object of the iterator which in our case will be the object of the class itself.

__iter__()方法将返回迭代器的对象,在我们的情况下,该对象将是类本身的对象。

And the __next__() method should return the next element every time it is called and should raise the StopIteration exception upon reaching the end.

__next__()方法应在每次调用时返回下一个元素,并在到达末尾时引发StopIteration异常。

Below we have a simple class Counting which will print the counting starting from 1 till the number that you provide while initializing the class.

下面我们有一个简单的Counting类,它将打印从1开始的数字,直到您在初始化该类时提供的数字为止。

演示地址

You can also try to call the iter() method on the object of the Counting class and then use the next() method on the iterator to print the values one by one.

您也可以尝试在Counting类的对象上调用iter()方法,然后在迭代器上使用next()方法逐一打印值。

翻译自: https://www.studytonight.com/python/python-iterable-and-iterator

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值