一个账号 发表于 2020-3-21 12:47:33

Python iter() 函数

本帖最后由 一个账号 于 2020-3-25 19:45 编辑

Python iter() 函数

语法

iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

参数


参数描述
iterable可迭代对象
callable可调用的对象
sentinel首先调用 callable,如果 callable 的返回值等于 sentinel,则抛出 StopIteration 异常


描述

iter() 函数用来生成迭代器。

返回值

返回一个迭代器对象。

例子

>>> iter()
<list_iterator object at 0x0000022B198325B0>
>>> list(iter())

>>> for i in iter():
      print(i)

      
1
2
3
4
>>> import random
>>> class Test:
        def __call__(self):
                return random.randint(1, 10)

       
>>> t = Test()
>>> for i in iter(t, 8):   # 当 t 的值是 8 的时候,结束循环
        print(i)

       
4
3
1
5
6
10
10
1
5
9
7
9
>>> li = []
>>> for i in iter(input, "quit"):    # 让用户输入信息,输入 quit 停止
        li.append(i)

       
hello world
abc
def
blablabla
Python

FishC
quit
>>> li
['hello world', 'abc', 'def', 'blablabla', 'Python', '', 'FishC']
页: [1]
查看完整版本: Python iter() 函数