鱼C论坛

 找回密码
 立即注册
查看: 2295|回复: 0

[技术交流] Python iter() 函数

[复制链接]
发表于 2020-3-21 12:47:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

Python iter() 函数


语法

  1. iter(iterable) -> iterator
  2. iter(callable, sentinel) -> iterator
复制代码


参数

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


描述

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

返回值

返回一个迭代器对象。

例子

  1. >>> iter([1, 2, 3, 4])
  2. <list_iterator object at 0x0000022B198325B0>
  3. >>> list(iter([1, 2, 3, 4]))
  4. [1, 2, 3, 4]
  5. >>> for i in iter([1, 2, 3, 4]):
  6.         print(i)

  7.         
  8. 1
  9. 2
  10. 3
  11. 4
  12. >>> import random
  13. >>> class Test:
  14.         def __call__(self):
  15.                 return random.randint(1, 10)

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

  20.        
  21. 4
  22. 3
  23. 1
  24. 5
  25. 6
  26. 10
  27. 10
  28. 1
  29. 5
  30. 9
  31. 7
  32. 9
  33. >>> li = []
  34. >>> for i in iter(input, "quit"):    # 让用户输入信息,输入 quit 停止
  35.         li.append(i)

  36.        
  37. hello world
  38. abc
  39. def
  40. blablabla
  41. Python

  42. FishC
  43. quit
  44. >>> li
  45. ['hello world', 'abc', 'def', 'blablabla', 'Python', '', 'FishC']
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-10 21:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表