python中iter的用途是什么? [英] What is the use of iter in python?

查看:997
本文介绍了python中iter的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中使用iter函数有什么用?

What is the use of using the iter function in python?

代替:

for i in range(8):
  print i

我也可以使用iter:

for iter in range(8):
  print iter

推荐答案

首先:

First of all: iter() normally is a function. Your code masks the function by using a local variable with the same name. You can do this with any built-in Python object.

换句话说,您不是在这里使用iter()功能.您正在使用恰好使用相同名称的for循环变量.您可以将其称为dict,它与字典无关,而与Guido选择咖啡有关.从for循环的角度来看,两个示例之间没有没有差异.

In other words, you are not using the iter() function here. You are using a for loop variable that happens to use the same name. You could have called it dict and it would be no more about dictionaries than it is about Guido's choice of coffee. From the perspective of the for loop, there is no difference between your two examples.

否则,您将使用iter()函数生成迭代器类型;具有.next()方法(在Python 3中为.__next__())的对象.

You'd otherwise use the iter() function to produce an iterator type; an object that has a .next() method (.__next__() in Python 3).

for循环通常为您执行此操作.当使用可以产生迭代器的对象时,for语句将使用C等效项,在其上调用iter().如果要对该对象执行其他特定于迭代器的操作,则只会使用iter().

The for loop does this for you, normally. When using an object that can produce an iterator, the for statement will use the C equivalent of calling iter() on it. You would only use iter() if you were doing other iterator-specific stuff with the object.

这篇关于python中iter的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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