Parisgabriel:python Full Stack engineer (0 basics to Mastery) Tutorial 22nd (iterator, byte string)

Source: Internet
Author: User
Tags generator generator iterable

ParisgabrielStick to Handwriting day by day a decision hold on for a few years to dream for faith

                      Python ai from beginner to proficient


Iterator Iterator:
    Must be an object in <> brackets

What is an iterator?
Iterators are tools that access an iterative object
An iterator is an object (instance) returned with the ITER (obj) function
Iterators can use the next (IT) function to get data for an iterative object

Iterator functions Iter and next
  iter (iterable) returns an iterator from an iterative object, and Iterable must be an object that can provide an iterator
  Next (iterator) gets the next record from the iterator iterator, triggering the stopiteration exception if the next record cannot be obtained

Description:
Iterators can only forward values , not back
Use the iter function to return an iterator to an iterative object
function:
The iterator object can get the next element with the next function.

Example:
L = [2, 3, 5, 7]
it = iter (l) # returns an iterator with an L object that can access L, an IT-bound iterator
Next (IT) # 2
Next (IT) # 3
Next (IT) # 5
Next (IT) # 7
Next (IT) # Stopiteration notifications (no data)

it = ITER (range (1, 10, 30))
Next (IT) # 1
Next (IT) # 4
Next (IT) # 7
Next (IT) # stopiteration

To access an iterator object with an iterator:

L = [2, 3, 5, 7] forXinchL:Print(x)Else:    Print('End of Cycle') It= ITER (L)#get an iterator from L whileTrue:Try: x=Next (IT)Print(x)exceptstopiteration:Print("End of Cycle")         Break


Generator Generator (Python 2.5 and later)
What is a generator?
A builder is an object that can provide data dynamically , and a generator object is also an iterative object (instance)
  Dynamic is the active current generation of data

There are two types of generators:
1. Generator Functions
2. Generator Expressions

Definition of generator function
A function with a yield statement is a generator function, which is called to return a generator object
Yield translated into (generated or generated)

yield Statement
  Grammar:
Yield expression
  Description
Yield is used in the DEF function to use the Function Builder function
Yield is used to generate data for use by the next (IT) function of the iterator
Yield single-step generation data can be one or many within a function

Instance:

 #   This example shows how to generate a range of natural numbers with a generator function  def   Myinteger (n): I  = 0 #< /span> natural number starting from 0  while  i < n:  yield   I i += 1for  x in  myinteger (3 print  (x) 

Generator Function Description: The call to
Builder function returns a raw builder object , builder object Yes an iterator object
in the raw builder function call return  will Triggers a stopiteration exception
Builder expression:
Syntax:
(expression for variable in iterate object [     If truth expression])
Description:
if clause can omit
effect:
Create with derivation a new builder
Example:
Gen = (x * * 2 F or x in range (1, 5))
it = iter (gen)
Next (IT) # 1
Next (IT) # 4
Next (IT) # 9
Next (it ) #
Next (IT) # stopiteration
Iteration tool function
The function of the iteration tool function is to generate a personalization Iteration Object

Function:
Zip (iter1[, iter2[, ...]) Returns a Zip object that is used to generate tuples , the number of which is determined by the smallest iteration object

Enumerate (iterable[, start]) generates an indexed enumeration object that returns the iteration type as an index-value pair (Index-value pair), the default index is zero-based, or it can be specified with the start

Example: Numbers= [10086, 10000, 10010, 9558] Names= ['China Mobile','China Telecom','China Unicom']   forTinchZip (numbers, names):Print(t) forX, yinchZip (numbers, names):Print(Y,'the customer service phone number is:', x) x, y= (10086,'China Mobile')#sequence Assignment
example of implementation of the ZIP function  2: def Myzip (Iter1, iter2):       = ITER (Iter1)  #  takes out an iterator      it2 = iter (iter2      )while  True:          = Next (it1)          = Next (it2)          yield  (A, b)  for  in# can achieve the same function as Zip      print(t)
Enumerate example: Names= ['China Mobile','China Telecom','China Unicom']     forTinchEnumerate (names):Print(t) enumerate implementation method schematic:defMyEnum (iterable): it=iter (iterable) I=0 whiletrue:a=Next (IT)yield(i, a) I+ = 1

byte strings and byte arrays
Byte string bytes (also called byte sequence)
  Role:
    storing data in bytes
A byte string is an immutable sequence of bytes

 Bytes:
A byte is a unit of data that consists of 8 bits (bit) , which is the unit of data management for the computer.
Bytes are represented by integers in the range of 0 ~ 255 .

Create a literal value for an empty byte string
b = B '
B = B ""
B = B ""
B = B "" "" "" "

Create a literal value of a non-empty byte string
b = B ' ABCD '
b = B "ABCD"
b = B ' \x41\x42 '

The constructor of the byte string bytes
Bytes () Generates an empty byte string equivalent to B '
Bytes (Integer iteration object) # Initialize a byte string with an iterative object
Bytes (integer n) generates n byte strings with a value of 0
Bytes (string, encoding= ' utf-8 ') generates a byte string by converting it to an encoding

  Example:
b = bytes () # b = B '
b = Bytes (range (+)) # b = B ' ABCD '
b = Bytes (5) # b = B ' \x00\x00\x00\x00\x00 '
b = Bytes (' ABC Chinese ') # b=b ' abc\xe4\xb8\xad\xe6\x96\x87 '

bytes 's operation:
+ += * *=
< <= > >= = = =!
In/not in
Indexes and slices

Len (x)
Max (x)
MIN (x)
SUM (x)
Any (x)
All (x)


The difference between bytes and str :
 bytes Storage bytes (typically values in range (0, 256))
  str stores Unicode characters (usually values in 0~65535)


Conversion of bytes and Str
encoding (encode)
str------------> bytes
b = S.encode (encoding= ' utf-8 ')

Decoding (decode)
Bytes----------> str
s = B.decode (encoding= ' utf-8 ')


byte array bytearray
variable sequence of bytes

constructor for byte array: ByteArray
ByteArray () Creates an empty byte array
ByteArray (integer) Initializes an array of bytes with an iterator object
ByteArray (integer iteration object) generates n byte array with a value of 0
ByteArray (String, encoding= ' utf-8 ') generates a byte array with the conversion encoding of the string

ByteArray's Operation:
+ += * *=
< <= > >= = = =!
In/not in
Indexes and slices
(Byte arrays support assignment of indexes and slices, rules are indexed and tile assignment rules are the same list)

Cases:
ba = ByteArray (b ' ABCDEfG ')
Ba[0] = 65
Ba[-2] = 70

ByteArray method of:
Ba.clear () empty
Ba.append (n) append one byte (n is an integer of 0~255)
Ba.remove (value) deletes the first occurrence of the byte and, if it does not, triggers a valueerror error
Ba.reverse () byte order reversal
Ba.decode (encoding= ' Utf-8 ') # decoded to a string
Ba.find (sub[, Start[,end]) # Find Sub

Practice:
There is a collection:
s = {' Tang monk ', ' Goku ', ' Eight commandments ', ' Sand Monk '}
Use the For statement to iterate through all the elements as follows:
For x in S:
Print (x)
Else
Print (' Traversal end ')
Please rewrite the For statement above to implement with the while statement and iterator

Practice:
Write a generator function Myeven (start, stop)
This function is used to generate a series of even numbers from start to end of Stop (not included) in the interval
Def myeven (Start, stop):
....

Evens = List (Myeven (10, 20))
Print (Evens) # [10, 12, 14, 16, 18]
For x in Myeven (21, 30):
Print (x) # 22, 24, 26, 28

L = [x**2 for x in Myeven (3, 10)]
Print (L) # 16 36 64

Practice:
Known to have a list L
L = [2, 3, 5, 7]
Use the generator expression to get the number from this list to generate the square of the data in the list

Gen = ... # This is implemented here with a builder expression
L2 = List (gen) # L2 = [4, 9, 25, 49]

Practice:
Write a program that reads the text of any line and ends the input when the input is empty
To print an input with a line number:
Such as:
Please enter: hello< carriage return >
Please enter: world< carriage return >
Please enter: tarena< carriage return >
Please enter: < Enter > # Direct Enter end input
The output is as follows:
Line 1th: Hello
Line 2nd: World
Line 3rd: Tarena


Practice:
Write a program, enter a string from the keyboard into the s variable
1. Convert this string to a byte string, bind with variable B and print out B
2. Print the length of the string s and the length of the byte string b
3. Convert the B-byte string to a string with the variable s2 binding to determine if S2 and s are the same?

Practice:
1. Write a generator function primes generate prime number,
This generator function is primes (begin, end)
For example: [x for X in primes (10, 20)] will get the list
[11, 13, 17, 19]

Answer:

defGET_SS (x):ifX <=0:returnFalse forIinchRange (2, x):ifX% i = =0:returnFalsereturnTruedefprimes (begin, end):ifBegin <= 2orEnd <= 2:        Pass     forXinchrange (begin, end):ifGET_SS (x):yieldXL= [x forXinchPrimes (10, 20)]PrintL

2. Write a generator function to generate the number of the first n of the Fibonacci sequence
1 1 2 3 5 8 13
def Fibonacci (N):
...
Yield ...
1) Output first 20 numbers:
For X in Fibonacci (20):
Print (x)
2) Print the first 40 numbers and:
Print (SUM (Fibonacci (40)))

Answer:

def Fibonacci (N):     = [1, 1]    for in  Range (n):        = l[x] + l[x + 1]        l.append (s)     return L Print (Fibonacci ()) Print (Sum (Fibonacci (40)))


3. Write program print Yang Hui triangle (print only 6 layers)
1
1 1
1 2 1
1 3 3 1
1 4 6) 4 1
1 5 10 10 5 1


Thinking:
L = [2, 3, 5, 7]
L2 = [x * * 2 for x in L] # list derivation
it = iter (L2)
Print (Next (IT) # 4
L[1] = 10
Print (Next (IT) # 9

L = [2, 3, 5, 7]
G3 = (x * * 2 for X in L) # Generator expression
it = iter (G3)
Print (Next (IT) # 4
L[1] = 10
Print (Next (IT) # 100

Parisgabriel:python Full Stack engineer (0 basics to Mastery) Tutorial 22nd (iterator, byte string)

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.