python iter函数用法
iter函数用法简述
Python 3中关于iter(object[, sentinel)]方法有两个参数。
使用iter(object)这种形式比较常见。
iter(object, sentinel)这种形式一般较少使用
1,iter(object)
Python官方文档对于这种形式的解释很容易理解。
此时,object必须是集合对象,且支持迭代协议(iteration protocol)或者支持序列协议(sequence protocol)。
说白了,也就是实现了__iter__()方法或者__getitem__()方法。
l = [1, 2, 3]for i in iter(l):print(i)
2,iter(object, sentinel)
Python官方文档对于这种形式的解释是:“ If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__()
method; if the value returned is equal to sentinel,StopIteration
will be raised, otherwise the value will be returned.”。
这句话的意思是说:如果传递了第二个参数,则object必须是一个可调用的对象(如,函数)。此时,iter创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用object。
如果__next__的返回值等于sentinel,则抛出StopIteration异常,否则返回下一个值。
class TestIter(object):def __init__(self):self.l=[1,2,3,4,5]self.i=iter(self.l)def __call__(self): #定义了__call__方法的类的实例是可调用的item = next(self.i)print ("__call__ is called,which would return",item)return itemdef __iter__(self): #支持迭代协议(即定义有__iter__()函数)print ("__iter__ is called!!")return iter(self.l)t = TestIter() # t是可调用的t1 = iter(t, 3) # t必须是callable的,否则无法返回callable_iteratorprint(callable(t))for i in t1:print(i)
# 它每次在调用的时候,都会调用__call__函数,并且最后输出3就停止了。True
__call__ is called,which would return 1
1
__call__ is called,which would return 2
2
__call__ is called,which would return 3
在文件读取时使用:
import os
import hashlibdef bytes2human(n):# 文件大小字节单位转换symbols = ('K', 'M', 'G', 'T', 'P', 'E')prefix = {}for i, s in enumerate(symbols):# << 左移” 左移一位表示乘2 即1 << 1=2,二位就表示4 即1 << 2=4,# 10位就表示1024 即1 << 10=1024 就是2的n次方prefix[s] = 1 << (i + 1) * 10for s in reversed(symbols):if n >= prefix[s]:value = float(n) / prefix[s]return '%.2f%s' % (value, s)return "%sB" % ndef get_md5(file_path):"""得到文件MD5:param file_path::return:"""if os.path.isfile(file_path):file_size = os.stat(file_path).st_sizemd5_obj = hashlib.md5() # hashlibf = open(file_path, 'rb') # 打开文件read_size = 0while read_size < file_size:read_byte = f.read(8192)md5_obj.update(read_byte) # update md5read_size += len(read_byte)hash_code = md5_obj.hexdigest() # get md5 hexdigestf.close()print('file: [{}] \nsize: [{}] \nmd5: [{}]'.format(file_path, bytes2human(read_size), hash_code))return str(hash_code)def get_filemd5(file_path):# 使用迭代器读取文件获得MD5if os.path.isfile(file_path):file_size = os.stat(file_path).st_sizemd5_obj = hashlib.md5() # hashlibf = open(file_path, 'rb') # 打开文件read_size = 1024for chunk in iter(lambda: f.read(read_size), b''): # 使用迭代器读取文件获得MD5md5_obj.update(chunk)hash_code = md5_obj.hexdigest() # get md5 hexdigestf.close()print('file: [{}] \nsize: [{}] \nmd5: [{}]'.format(file_path, bytes2human(file_size), hash_code))return str(hash_code)if __name__ == '__main__':md5 = get_md5(r'C:\README.md')md5_1 = get_filemd5(r'C:\README.md')------------------------输出file: [C:\README.md]
size: [941B]
md5: [d22b8f76dcd8cfbfd4669d9d8101077e]
file: [C:\README.md]
size: [941B]
md5: [d22b8f76dcd8cfbfd4669d9d8101077e]
转载于:https://www.cnblogs.com/xiao-apple36/p/9519114.html
python iter函数用法相关推荐
- python中iter函数_Python iter()函数用法详解
Python iter()函数用法实例分析 本文实例讲述了Python iter()函数用法.分享给大家供大家参考,具体如下: python中的迭代器用起来非常灵巧,不仅可以迭代序列,也可以迭代表现出 ...
- python之函数用法islower()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法islower() #http://www.runoob.com/python/att ...
- python之函数用法startswith()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法startswith() #http://www.runoob.com/python/ ...
- python之函数用法__getitem__()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法__getitem__() #http://www.cnblogs.com/hongf ...
- python之函数用法capitalize()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法capitalize()#capitalize() #说明:将字符串的第一个字母变成大 ...
- python之函数用法isupper()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法isupper() #http://www.runoob.com/python/att ...
- Python range() 函数用法细解(附猴子吃桃问题引例)
Python range() 函数用法细解 --步入大学,好多计算机系的同学可能专业课学c或者java,但是随着python变成语言的崛起,往往一些学校也会要求学生们学习Python这门编程语言(我们 ...
- [转载] python iter( )函数
参考链接: Python iter() python中的迭代器用起来非常灵巧,不仅可以迭代序列,也可以迭代表现出序列行为的对象,例如字典的键.一个文件的行,等等. 迭代器就是有一个next()方法的对 ...
- python print函数用法_Python3.2中Print函数用法实例详解
本文实例讲述了Python3.2中Print函数用法.分享给大家供大家参考.具体分析如下: 1. 输出字符串 >>> strHello = 'Hello World' >> ...
- python所有函数用法_python函数用法总结
空函数 如果想定义一个什么事也不做的空函数,可以用pass语句: def nop(): pass pass语句什么都不做,那有什么用?实际上pass可以用来作为占位符,比如现在还没想好怎么写函数的代码 ...
最新文章
- java接口防抖_前端性能优化:高频执行事件/方法的防抖
- Java计算时间差、日期差总结(亲测)
- spring mvc学习(19):cookievalue注解(显示cookie的值,默认必须有值)
- Linux驱动小技巧 | 利用DRIVER_ATTR实现调用内核函数
- c html联调,JS与native 交互简单应用
- 关于CAS服务器磁盘占用的问题,锁定目录惹的祸
- mysql 连接错误The server time zone value ‘?????????‘
- Python 爬虫工具 —— fake_useragent
- J2EE中使用jstl报http //java sun com/jsp/jstl/core cannot be reso
- Android View onVisibilityChanged onAttachedToWindow onDetachedFromWindow
- 最新win7/win10/XP系统下载_「装机系统」_百度云
- python numpy官方文档_[ Numpy中文文档 ] 介绍 - pytorch中文网
- 学生想学信息学奥赛: DEV-C++的安装与介绍
- 浅谈运营商行业业务的发展方向
- Spark的基本工作流程
- 阿里云win2016服务器部署jdk+tomcat填坑
- oracle12c彻底关闭omf,11g OMF管理时 db_unique_name的一个大小写疑问
- 安卓zip解压软件_暴力破解~解压缩神器!
- python发送esc_使用win32prin将一行文本发送到Python中的ESC/POS打印机
- 一个sql server2005分页的存储过程