Detailed introduction to Python's built-in iter function
英文文档:
iter(object[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.
One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:
with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line)
说明:
2. 当第二个参数不提供时,第一个参数必须是一个支持可迭代协议(即实现了iter()方法)的集合(字典、集合、不可变集合),或者支持序列协议(即实现了getitem()方法,方法接收一个从0开始的整数参数)的序列(元组、列表、字符串),否则将报错。
>>> a = iter({'A':1,'B':2}) #字典集合 >>> a <dict_keyiterator object at 0x03FB8A50> >>> next(a) 'A' >>> next(a) 'B' >>> next(a) Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> next(a) StopIteration >>> a = iter('abcd') #字符串序列 >>> a <str_iterator object at 0x03FB4FB0> >>> next(a) 'a' >>> next(a) 'b' >>> next(a) 'c' >>> next(a) 'd' >>> next(a) Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> next(a) StopIteration
3. 当第二个参数sentinel提供时,第一个参数必须是一个可被调用对象。创建的迭代对象,在调用next方法的时候会调用这个可被调用对象,当返回值和sentinel值相等时,将抛出StopIteration异常, 终止迭代。
# 定义类 >>> class IterTest: def __init__(self): self.start = 0 self.end = 10 def get_next_value(self): current = self.start if current < self.end: self.start += 1 else: raise StopIteration return current >>> iterTest = IterTest() #实例化类 >>> a = iter(iterTest.get_next_value,4) # iterTest.get_next_value为可调用对象,sentinel值为4 >>> a <callable_iterator object at 0x03078D30> >>> next(a) >>> next(a) >>> next(a) >>> next(a) >>> next(a) #迭代到4终止 Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> next(a) StopIteration
The above is the detailed content of Detailed introduction to Python's built-in iter function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

Using python in Linux terminal...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
