• 技术文章 >Python技术 >Python基础教程

    Python基础:iter函数的两个参数

    2020-10-27 16:37:56原创6429
    Python中的函数非常多,而且使用频繁。今天小编为大家带来Python中iter函数的用法,后续的文章也会有涉及这个函数的运用。


    Python 3中关于iter (object[, sentinel)] 方法有两个参数。

    使用iter (object) 这种形式比较常见,iter (object, sentinel) 这种形式一般较少使用。


    1.iter (object)


    Python官方文档对于这种形式的解释很容易理解。

    此时,object必须是集合对象,且支持迭代协议(iteration protocol)或者支持序列协议(sequence protocol)。

    说白了,也就是实现了__iter__() 方法或者 __getitem__() 方法


    1

    2

    3

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">l = [1, 2, 3]

      for i in iter(l):

          print(i)<br></span></p>


    2.iter (object, sentinel)


    Python官方文档对于这种形式的解释是:如果传递了第二个参数,则object必须是一个可调用的对象(如函数)。此时,iter创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用object。

    如果__next__的返回值等于sentinel,则抛出StopIteration异常,否则返回下一个值。


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">    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<br></span></p>


    在文件读取时使用:


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">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]<br></span></p>


    根据示例来看,iter函数还是比较容易理解的,更多Python学习推荐:PyThon学习网教学中心

    专题推荐:python中iter函数
    上一篇:python开发环境哪个好用?如何搭建? 下一篇:python正则表达式是什么?怎么用?

    相关文章推荐

    • 关于Python中openpyxl使用iter_rows()的方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网