Iterator Iterator and Generator Generator
What is an iterator:
Iterator is a way to access iterable objects. Iterators can be used to access iterable objects. Iterators refer to the objects returned by iter (iterable objects).
Iterators can use the next(it) function to get the data of the iterable objects.
Iterator functions iter and next
iter(iterable) Returns an iterator from the iterable object, iterable must be an object that can provide an iteratornext(iterable) Get the next record from the iterable iterable. If the next record cannot be obtained, a StopIterator exception will be triggered
Iterator description:
Iterators can only take values forward, not backwards. The iter function can return an iterable object using the iter function
Example :
L = [2, 3, 5, 7] it = iter(L) # use iter to return an iterator bound with it next(it) # 2 #Use next(it) to get the elements in L with an iterator next(it) # 3 next(it) # 5 next(it) # 7 next(it) # StopIterator #Notify the next caller that there is no more data
#Use the iterator to get the data of the range object >>> it = iter(range(1, 10, 3)) >>> next(it) 1 >>> next(it) 4 >>> next(it) 7 >>> next(it) StopIteration Example: L = [2, 3, 5, 7]
# use for loop to access data in iterable object for x in L: print(x) print('=*= ' * 10+'=*=') # use while loop to access data in iterable object # First step, let L give us an iterator it = iter(L) # In the second step, the loop uses the it iterator to get the data in L until StopIteration while True: try: x = next(it) print(x) except StopIteration: breakExercise:
It is known that there is a set:
s=('ICBC', 'Construction Bank', 'Bank of China', 'Agricultural Bank')
1. Use the for statement to traverse the elements in the set and print
2. Change the above for statement to Into a while statement to achieve the same function as above
s = ('ICBC', 'Construction Bank', 'Bank of China', 'Agricultural Bank') for i in s: print(i) print('=*= ' * 10 + '=*=') def iterator(s): it=iter(s) while True: try: i=next(it) print(i) except: break if __name__ == '__main__': s = ('ICBC', 'Construction Bank', 'Bank of China', 'Agricultural Bank') iterator(s)
Generator generator (python2.5 and later)
What is a generator:
A generator is an object that can dynamically provide data, and a generator object is also an iterable objectThere are two types of generators:
generator functiongenerator expression
Generator function definition:
A function containing a yield statement is a generator function, which when called will return a generator objectyield translated as (produce or generate)
yield statement
Syntax:yield expression
description:
yield is used in def functions, the purpose is to use this function as a generator function
yield is used to generate data and provide the next(it) function to use
Example:
Write a generator function my_integer(n) to generate integers from 1 to n:
def my_integer(n): i=1# Initialize the variable i first and set it to the starting number while i <n: #The loop judges whether the termination point has been reached, if not, generate yield i# generate integer i+=1#Control loop condition if __name__ == '__main__': for i in my_integer(100): print(i)practise:
''' Write a function, myodd(start,stop) All odd numbers used to generate start start stop (exclusive) end L=[x for x in myodd(1,10)] print(L)#[1,3,5,7,9] for x in myodd(10,20): print(x) #11,13,15,17,19 ''' def myodd(start, stop): while start < stop: if start % 2: # same as start%2==1 yield start start += 1 if __name__ == '__main__': L = [x for x in myodd(1, 10)] print(L) # [1,3,5,7,9] for x in myodd(10, 20): print(x) # 11,13,15,17,19
Generator expression:
Syntax:(expression for variable in iterable object [if truth expression])
Note: the if part in [] can be omitted
:
use deduction to generate a generator
Example:
gen = (x ** 2 for x in range(1, 5)) it = iter (gen) next(it) # 1 next(it) # 4 next(it) # 9 next(it) # 16 next(it) # StopIteration
Iteration utility function:
The role of the iteration tool function is to generate a personalized iterable objectzip(iter1[,iter2, ...])
Returns a zip object, which is used to generate a tuple, the number of which is determined by the smallest iterable object, and the content of the tuple is the full amount of elements in iterable objects iter1 and iter2enumerate(iterable[,start])
Generate an indexed enumeration object, the returned iteration type is an index-value pair (index-value) pair, the default index starts from zero, you can also specify it with startExample :
#zip example one numbers = [10086, 10000, 10010, 95588] name = ['China Mobile', 'China Telecom', 'China Unicom'] for t in zip(numbers, name): print(t) # print(dict(zip(name,numbers ))) #zip example two # This example shows the internal implementation of the zip function def myzip(iter1, iter2): it1 = iter(iter1) it2 = iter(iter2) try: while True: a = next(it1) b = next(it2) yield (a, b) except: pass numbers = [10086, 10000, 10010, 95588] name = ['China Mobile', 'China Telecom', 'China Unicom'] for t in myzip(numbers, name): print(t) #zip example three numbers = [10086, 10000, 10010, 95588] name = ['China Mobile', 'China Telecom', 'China Unicom'] for t in zip(range(1,1111),numbers, name): print(t) # print(dict(zip(name,numbers ))) #enumerate example-1 # This example shows the usage of enumerate names = ['China Mobile', 'China Telecom', 'China Unicom'] for t in enumerate(names): print(t) print('*'*20) for t in enumerate(names,1): print(t) #enumerate example-2 # This example shows the usage of enumerate names = ['China Mobile', 'China Telecom', 'China Unicom'] for a,t in enumerate(names,1): print('Sequence number',a,'------>',t) #Equivalent to it=iter(enumerate(names,1)) while True: try: k,n=next(it) print('Sequence number',k,'------>',n) except StopIteration: break
Exercise:
Write a program, read in any line of text data, when you enter a blank line, end the input
and print the input result with the line number: For
example:
Please enter: hello<Enter>
Please enter: tarena<Enter>
Please enter: bye<Enter>
Please input:<Enter> The
output is as follows;
Line 1: hello
Line 2: tarena
Line 3: bye
def input_text(): '''Read in the text data entered by the keyboard, form a list and return ''' L = [] while True: str_ = input('Please input:') if not str_: break L.append(str_) return L def output_text(L): for t in enumerate(L, 1): print('Line %d: %s' % t) if __name__ == '__main__': text_L = input_text() output_text(text_L)
Byte strings and byte arrays
byte string (also called byte sequence) bytes
Role:Store data in bytes
Description:
Byte strings are immutable sequences
Bytes are integers between 0 and 255
Creates a literal value of the empty byte string
b''b""
b''''''
b""""""
Creates a literal value of a non-empty byte string
B=b'hello'B=b"hello"
B=b'''abcd'''
B=b"""abcd"""
B=b'abc\n123'
B=b'\x41\x42'
Byte string constructor:
bytes() generates an empty byte string equivalent to b''bytes(integer iterable object) initializes a byte string
bytes(integer n) with an iterable object generates n byte strings with a value of 0
bytes(string ,encoding='utf-8') generate a byte string with the conversion encoding of the byte string
Operations on bytes:
+ += * *=< <= > >= == !=
in / not in
indexing and slicing
in / not in example: B=b'ABCDE' 0x41 in B # True
Functions for sequences:
len() max min sum() any() all() can be used for byte strings
Sequence method:see:
help(bytes)
The difference between bytes and str:
bytes Store bytes (0~255)str Store characters
bytes and str conversion
编码(encode)str ---------> bytes
b=s.encode(encoding='utf-8')
解码(decode)
bytes -------------> str
s=b.decode(encoding='utf-8')
例:
b='Hello'.encode('utf-8') print(b) # b'\xe4\xbd\xa0\xe5\xa5\xbd' s=b.decode('utf-8') print(s) # 'Hello'
bytearray
mutable sequence of bytesCreate function bytearray
bytearray() creates an empty byte arraybytearray(integer)
bytearray(integer iterable object)
bytearray(string, encoding='utf-8')
operation:
+ += * *=
< <= > >= == !=
in / not in
index index / slice slice
(byte array can be indexed and sliced assignment, assignment rules are the same as list index and slice assignment)
Example:
ba = bytearray(b'abcdefg') ba[0] = 0x41 #ba = bytearray(b'Abcdefg') ba[1::2] = bytearray(b'BDF') #Modify bdf to uppercase
Exercise:
1. Use a generator function to generate the first n numbers of the Fibonacci sequence
1 1 2 3 5 8 13 ...
def fibonacci(n):
...
yield ..
1) Output the first 20 numbers
2) Find the sum of the first 30 numbers
2. Write a program to print the Yanghui triangle (only 6 layers are printed)