|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 一个账号 于 2020-3-25 19:45 编辑
Python iter() 函数
语法
- iter(iterable) -> iterator
- iter(callable, sentinel) -> iterator
复制代码
参数
参数 | 描述 | iterable | 可迭代对象 | callable | 可调用的对象 | sentinel | 首先调用 callable,如果 callable 的返回值等于 sentinel,则抛出 StopIteration 异常 |
描述
iter() 函数用来生成迭代器。
返回值
返回一个迭代器对象。
例子
- >>> iter([1, 2, 3, 4])
- <list_iterator object at 0x0000022B198325B0>
- >>> list(iter([1, 2, 3, 4]))
- [1, 2, 3, 4]
- >>> for i in iter([1, 2, 3, 4]):
- 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']
复制代码 |
|