Python3中迭代器介绍

x33g5p2x  于2021-11-11 转载在 Python  
字(1.8k)|赞(0)|评价(0)|浏览(276)

    Python中一个可迭代对象(iterable object)是一个实现了__iter__方法的对象,它应该返回一个迭代器对象(iterator object)。迭代器是一个实现__next__方法的对象,它应该返回它的可迭代对象的下一个元素,并在没有可用元素时触发StopIteration异常。

    当我们使用for循环遍历任何可迭代对象时,它在内部使用iter()方法获取迭代器对象,该迭代器对象进一步使用next()方法进行迭代。此方法触发StopIteration以表示迭代结束。

    Python中大多数内置容器,如列表、元组、字符串等都是可迭代的。它们是iterable但不是iterator,把它们从iterable变成iterator可以使用iter()函数。

    测试代码如下:

  1. # reference: https://www.programiz.com/python-programming/iterator
  2. my_list = [1, 3, 5] # define a list
  3. if 0:
  4. my_iter = iter(my_list) # get an iterator using iter()
  5. print(next(my_iter)) # iterate through it using next()
  6. print(my_iter.__next__()) # next(obj) is name as obj.__next__()
  7. print(my_iter.__next__()) # 5
  8. #print(my_iter.__next__()) # this will raise error(StopIteration), no items left
  9. else: # use the for loop
  10. for element in iter(my_list): # 迭代器对象可以使用for语句进行遍历
  11. print(element, end=" ")
  12. '''
  13. for element in iterable:
  14. # do something with element
  15. Is actually implemented as:
  16. # create an iterator object from that iterable
  17. iter_obj = iter(iterable)
  18. while True: # infinite loop
  19. try:
  20. # get the next item
  21. element = next(iter_obj)
  22. # do something with element
  23. except StopIteration:
  24. # if StopIteration is raised, break from loop
  25. break
  26. '''
  27. # reference: https://www.geeksforgeeks.org/iterators-in-python/
  28. class Test:
  29. def __init__(self, limit):
  30. self.limit = limit
  31. # Creates iterator object, Called when iteration is initialized
  32. def __iter__(self):
  33. self.x = 10
  34. return self
  35. # To move to next element. In Python 3, we should replace next with __next__
  36. def __next__(self):
  37. # Store current value ofx
  38. x = self.x
  39. # Stop iteration if limit is reached
  40. if x > self.limit:
  41. raise StopIteration
  42. # Else increment and return old value
  43. self.x = x + 1
  44. return x
  45. # Prints numbers from 10 to 15
  46. print("\n")
  47. for i in Test(15):
  48. print(i, end=" ")
  49. print("\n")
  50. value = iter(Test(11))
  51. print(next(value))
  52. print(next(value))
  53. #print(next(value)) # raise StopIteration
  54. print("test finish")

    GitHubhttps://github.com/fengbingchun/Python_Test

相关文章