关于python中可迭代对象和迭代器的一些理解

《关于python中可迭代对象和迭代器的一些理解》 关于python中可迭代对象和迭代器的一些理解

很多 python 教程中,对 python 的解释不容易理解,本文记录自己的理解和体会,是对迭代器和生成器的初步理解

加小编Python学习群:943752371可以获取各类Python学习资料!

一、关于迭代的认识

给定一个列表、元祖、字典、甚至字符串,我们使用 for 去遍历,这样我们叫迭代

  • 1、列表的迭代

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>list1 = [‘哈哈’, ‘西西’, ‘嘻嘻’]
for x in list1:
print(x)
复制代码
</pre>

  • 2、列表中需要迭代出下标使用 enumerate

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>list1 = [‘哈哈’, ‘西西’, ‘嘻嘻’]
for index, value in enumerate(list1):
print(index, value)
复制代码
</pre>

  • 3、元祖和字符串的迭代与列表的类似,一样的可以使用 enumerate 进行下标迭代
  • 4、字典的迭代方式一

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>dict1 = {‘name’: ‘张三’, ‘age’: 20, ‘gender’: ‘男’}
for item in dict1:
print(item)
复制代码
</pre>

  • 5、字典的迭代方式二

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>dict1 = {‘name’: ‘张三’, ‘age’: 20, ‘gender’: ‘男’}
for key in dict1.keys():
print(key)
复制代码
</pre>

  • 6、字典的迭代方式三

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>dict1 = {‘name’: ‘张三’, ‘age’: 20, ‘gender’: ‘男’}
for value in dict1.values():
print(value)
复制代码
</pre>

  • 7、字典的迭代方式四

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>dict1 = {‘name’: ‘张三’, ‘age’: 20, ‘gender’: ‘男’}
for k, v in dict1.items():
print(k, v)
复制代码
</pre>

二、可迭代与迭代器的区别

  • 1、可迭代一般都可以使用 for 来遍历
  • 2、迭代器不仅仅可以使用 for 遍历还可以使用 next() 函数一次获取一个元素
  • 3、可迭代转换迭代对象使用 iter(可迭代对象)
  • 4、判断可迭代对象与迭代器的方式

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>from collections.abc import Iterator, Iterable

Iterable 表示可迭代对象

Iterator 表示迭代器

list1 = [1, 2, 3]
print(isinstance(list1, Iterator))
print(isinstance(list1, Iterable))
print(isinstance(iter(list1), Iterator))
复制代码
</pre>

  • 5、集合数据类型如 list 、 dict 、 str 等是 Iterable 但不是 Iterator ,不过可以通过iter() 函数获得一个 Iterator 对象

三、自己实现一个可迭代的对象

  • 1、方式一(在类中实现 getitem 魔法函数)

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>from collections.abc import Iterator, Iterable
class Company(object):
def init(self, employee_list):
self.employee = employee_list
def getitem(self, item):
return self.employee[item]
if name == “main“:
company = Company([‘张三’, ‘李四’, ‘王五’])
print(isinstance(company, Iterable))
print(isinstance(company, Iterator))
print(isinstance(iter(company), Iterator))
for item in company:
print(item)
复制代码
</pre>

  • 2、方式二(在类中实现 iter 魔法函数,需要结合 next 魔法函数) 其实已经是迭代器

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;”>from collections.abc import Iterator, Iterable
class Company(object):
def init(self, employee_list):
self.employee = employee_list
self.index = 0
def iter(self):
return self

def next(self):
try:
current_val = self.employee[self.index]
except IndexError:
raise StopIteration
self.index += 1
return current_val
if name == “main“:
company = Company([‘张三’, ‘李四’, ‘王五’])
print(isinstance(company, Iterable))
print(isinstance(company, Iterator))
for item in company:
print(item)
复制代码
</pre>

  • 3、总结
  • 1. iter 内置函数会调用 iter 魔法函数,如果没有 iter 魔法函数就会去调用 getitem 魔法函数
  • 通过 isinstance(company, Iterable) 判断对象是否可迭代
  • 通过 isinstance(company, Iterator) 判断对象是否为迭代器
  • 可迭代器对象不代表是迭代器,但是可以通过 iter() 函数将可迭代的转换为迭代器
    原文作者:浪里小白龙q
    原文地址: https://www.jianshu.com/p/785b3d193d1c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞