Python 小技巧 069:iter() 函数的另一个用法
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)
运行结果:
1
2
3
4 已经了解!@zltzlt 新语法:res = []
while(i:=input()):
res.append(i) 永恒的蓝色梦想 发表于 2020-4-3 13:54
新语法:
:= 说:跟我们海象有啥关系 永恒的蓝色梦想 发表于 2020-4-3 13:54
新语法:
加一句提示:
res = []
print("Press <Enter> to exit.")
while(i:=input()):
res.append(i)
页:
[1]