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 item
def __iter__(self): #支持迭代协议(即定义有__iter__()函数)
print ("__iter__ is called!!")
return iter(self.l) t = TestIter() # t是可调用的
t1 = iter(t, 3) # t必须是callable的,否则无法返回callable_iterator
print(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 hashlib def 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) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f%s' % (value, s)
return "%sB" % n def get_md5(file_path):
"""
得到文件MD5
:param file_path:
:return:
"""
if os.path.isfile(file_path):
file_size = os.stat(file_path).st_size
md5_obj = hashlib.md5() # hashlib
f = open(file_path, 'rb') # 打开文件
read_size = 0
while read_size < file_size:
read_byte = f.read(8192)
md5_obj.update(read_byte) # update md5
read_size += len(read_byte)
hash_code = md5_obj.hexdigest() # get md5 hexdigest
f.close()
print('file: [{}] \nsize: [{}] \nmd5: [{}]'.format(
file_path, bytes2human(read_size), hash_code))
return str(hash_code) def get_filemd5(file_path):
# 使用迭代器读取文件获得MD5
if os.path.isfile(file_path):
file_size = os.stat(file_path).st_size
md5_obj = hashlib.md5() # hashlib
f = open(file_path, 'rb') # 打开文件
read_size = 1024
for chunk in iter(lambda: f.read(read_size), b''): # 使用迭代器读取文件获得MD5
md5_obj.update(chunk)
hash_code = md5_obj.hexdigest() # get md5 hexdigest
f.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]

  

  

  

  

python iter函数用法的更多相关文章

  1. python之函数用法iter()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法iter() #iter() #说明:对一个对象调用 iter() 就可以得到它的迭代 ...

  2. Python回调函数用法实例详解

    本文实例讲述了Python回调函数用法.分享给大家供大家参考.具体分析如下: 一.百度百科上对回调函数的解释: 回调函数就是一个通过函数指针调用的函数.如果你把函数的指针(地址)作为参数传递给另一个函 ...

  3. python之函数用法setdefault()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法setdefault() #D.get(k,d) #说明:k在D中,则返回 D[K], ...

  4. python之函数用法fromkeys()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法fromkeys() #fromkeys() #说明:用于创建一个新字典,以序列seq ...

  5. python之函数用法get()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法get() #http://www.runoob.com/python/att-dic ...

  6. python之函数用法capitalize()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法capitalize() #capitalize() #说明:将字符串的第一个字母变成 ...

  7. python之函数用法isupper()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法isupper() #http://www.runoob.com/python/att ...

  8. python之函数用法islower()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法islower() #http://www.runoob.com/python/att ...

  9. python之函数用法startswith()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法startswith() #http://www.runoob.com/python/ ...

随机推荐

  1. Oracle导入的常见语句

    登录sql > sqlplus / as sysdba 创建表空间sql > create tablespace TABLESPACE datafile 'e:\tables1.dbf' ...

  2. (10)The secret to great opportunities? The person you haven't met yet

    https://www.ted.com/talks/tanya_menon_the_secret_to_great_opportunities_the_person_you_haven_t_met_y ...

  3. c# 产生随机数 程序所在路径

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  4. BZOJ 1024 [SCOI2009]生日快乐 (搜索)

    1024: [SCOI2009]生日快乐 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 3025  Solved: 2201[Submit][Statu ...

  5. PI3HDX1204B

    PI3HDX1204B用于HDMI2.0 6Gpbs的中继器,它有可编程的高均衡,输出摆幅和去加重控制模式.当传输为6Gpbs时,最大的EQ是22dB. PI3HDX1240B的EQ,SW和去加重可以 ...

  6. MFCC

    在语音识别研究领域,音频特征的选择至关重要.在这里介绍一种非常成功的音频特征——Mel Frequency Cepstrum Coefficient(MFCC),中文名字为梅尔频率倒谱系数.MFCC特 ...

  7. 20) maven 项目结构:all in one

    这是最常见的项目结构 垂直结构 也是初学者常用的 也是小项目常用的 优点 全部代码在一个项目里,一目了然. 结构简单易于理解 一开始时小巧 缺点 随之而来的缺点也十分明显 前端项目,后端项目,接口项目 ...

  8. linux上安装rabbitMQ

    本次环境搭建centos7及Erlang环境otp_src_19.3.tar.gz 和rabbitmq-server-generic-unix-3.6.14.tar.zx RabbitMQ是流行的开源 ...

  9. Ng第二课:单变量线性回归(Linear Regression with One Variable)

    二.单变量线性回归(Linear Regression with One Variable) 2.1  模型表示 2.2  代价函数 2.3  代价函数的直观理解 2.4  梯度下降 2.5  梯度下 ...

  10. (转)MVC语法-基础

    好久没有关注微软的开发了,今天看到了MVC3,顺便学习学习,我觉得Razor是个不错的做法,比使用<%%>简单多了,而且好看.首先“_”开头的cshtml文档将不能在服务器上访问,和asp ...