Python iter function usage

Source: Internet
Author: User

A brief introduction to ITER function usage

There are two parameters for the ITER (object[, Sentinel) method in Python 3.

This form of use of ITER (object) is more common.

Iter (object, Sentinel) is generally less used in this form

1,iter (object)

The official Python documentation is easy to understand for this form of interpretation.

At this point, object must be a collection object and support an iterative protocol (iteration protocol) or a support sequence protocol (sequence protocol).

Plainly, that is, the __iter__ () method or the __getitem__ () method is implemented.

  L = [1, 2, 3] for    I in ITER (l):        print (i)

2,iter (object, Sentinel)

The official Python document explains this form: "If the second argument, Sentinel, is given, then object must be a callable object. The iterator created in this case would call object with no arguments for each call to its __next__() method; if the value retur Ned was equal to Sentinel, would be StopIteration raised, otherwise the value would be returned. "

If you pass the second argument, object must be a callable object (for example, a function). At this point, ITER creates an iterator object that is invoked each time the __next__ () method of the iterator object is called.

If the return value of __next__ equals Sentinel, the Stopiteration exception is thrown, otherwise the next value is returned.

    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): #支持迭代协议 (that is, defined with __iter__ () function)            print ("__iter__ is called!!")            Return iter (SELF.L)    t = Testiter ()  # T is callable    t1 = iter (T, 3)  # T must be callable, otherwise it cannot be returned Callable_ Iterator    Print (callable (t))    for i in T1:        print (i) # It calls the __call__ function every time it is called, and the last output 3 stops. True__call__ is Called,which would return 11__call__ be Called,which would return 22__call__ is Called,which would return 3

To use when a file is read:

Import Osimport hashlibdef Bytes2human (n): # File size byte unit conversion symbols = (' K ', ' M ', ' G ', ' T ', ' P ', ' E ') prefix = {} f Or I, s in enumerate (symbols): # << left shift one means multiply by 2 that is 1 << 1=2, two bits means 4 is 1 << 2=4, # 10 bits means 1024 That is, 1 << 10=1024 is 2 n prefix[s] = 1 << (i + 1) * Ten for S in reversed (symbols): if n >= pr Efix[s]: value = float (n)/prefix[s] return '%.2f%s '% (value, s) return "%SB"% ndef get_md5 (fi Le_path): "" "Get file MD5:p Aram 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 ') # opening file Read_si ze = 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.clo SE () print (' File: [{}] \nsize: [{}] \nmd5: [{}] '. Format (File_path, Bytes2human (read_size), Hash_code)) return str (hash_c ODE) def GET_FILEMD5 (File_path): # using iterators to read files get 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 ') # opening file Read_size = 1024 For chunk in ITER (Lambda:f.read (read_size), B '): # using iterators to read files get 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_m D5 (R ' C:\README.md ') Md5_1 = Get_filemd5 (R ' C:\README.md ')------------------------output file: [C:\README.md] Size: [941B] MD5: [d22b8f76dcd8cfbfd4669d9d8101077e]file: [C:\README.md] Size: [941B] MD5: [ D22B8F76DCD8CFBFD4669D9D8101077E]

  

  

  

  

Python iter function usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.