关于python中可迭代对象和迭代器的一些理解!
发布时间:2020-12-17 00:30:10 所属栏目:Python 来源:网络整理
导读:很多 python 教程中,对 python 的解释不容易理解,本文记录自己的理解和体会,是对迭代器和生成器的初步理解 一、关于迭代的认识 给定一个列表、元祖、字典、甚至字符串,我们使用 for 去遍历,这样我们叫迭代 1、列表的迭代 list1 = ['哈哈','西西','嘻嘻']f
很多 python 教程中,对 python 的解释不容易理解,本文记录自己的理解和体会,是对迭代器和生成器的初步理解 一、关于迭代的认识 给定一个列表、元祖、字典、甚至字符串,我们使用 for 去遍历,这样我们叫迭代
list1 = ['哈哈','西西','嘻嘻'] for x in list1: print(x)
list1 = ['哈哈','嘻嘻'] for index,value in enumerate(list1): print(index,value)
dict1 = {'name': '张三','age': 20,'gender': '男'} for item in dict1: print(item)
进群:960410445 即可获取数十套PDF哦! dict1 = {'name': '张三','gender': '男'} for key in dict1.keys(): print(key)
dict1 = {'name': '张三','gender': '男'} for value in dict1.values(): print(value)
dict1 = {'name': '张三','gender': '男'} for k,v in dict1.items(): print(k,v) 二、可迭代与迭代器的区别
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))
三、自己实现一个可迭代的对象
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)
from collections.abc import Iterator,employee_list): self.employee = employee_list self.index = 0 def __iter__(self): return self
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |