|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
iter() 函数除了获取可迭代对象的迭代器,还有另一个用法。
看一下帮助文档:
- >>> help(iter)
- Help on built-in function iter in module builtins:
- iter(...)
- iter(iterable) -> iterator
- iter(callable, sentinel) -> iterator
-
- Get an iterator from an object. In the first form, the argument must
- supply its own iterator, or be a sequence.
- In the second form, the callable is called until it returns the sentinel.
复制代码
它的第二种形式是:
- iter(callable, sentinel) -> iterator
复制代码
返回的也是一个迭代器。当函数 callable 调用的结果不为 sentinel 时,返回调用结果。否则退出循环。
iter() 函数可以在询问用户输入多行时用到:
- print("请输入多行文本(连按两次 <Enter> 键退出):")
- res = []
- for i in iter(input, ''):
- res.append(i)
- print("你输入的文本是:")
- print("\n".join(res))
复制代码
运行结果:
- 请输入多行文本(连按两次 <Enter> 键退出):
- asdasdasd
- fghfghfgh
- 你输入的文本是:
- asdasdasd
- fghfghfgh
复制代码
iter() 函数还能这样用:
- n = 0
- def f():
- global n
- n += 1
- return n
- for i in iter(f, 5): # 当 f() 不为 5 时继续循环
- print(i)
复制代码
运行结果:
|
|