Python builder, ternary expression, list-generated, dictionary-generated, generator-expression

Source: Internet
Author: User
Tags generator

What is a generator:
As long as there is a yield keyword inside the function, the result (the generator address) of the function name () is the generator,
Re-calling function does not execute function internal code
The generator itself has the _iter_ he _next_ function (i.e. the generator is an iterator)

Why Use Generators:
A builder is a way to customize iterators


Summarize the function of yield
1. Provide a way to customize iterators
2, yield can pause the function, return value

Yield He return
Same point: All are used within the function, can return a value, no type limit, no number limit
Difference: Return returns only one value at a time, and yield can return multiple values


1. Generator next value, for example 1:
def func (): #第一步: Defining functions
Print (' First1 ')
Print (' First2 ')
Print (' First3 ')
Yield 1 #暂停
Print (' Second1 ')
Print (' Second2 ')
Print (' Second3 ')
Yield 2 #暂停
Print (' third ')
Yield 3 #暂停
Print (' fourth ')
G=func () #调用函数,do not execute function body code(just got the generatori.e. iterators)
Print (g)
Res1=next (g) #把yieldBehind thereturn valueAssign a value tores1#取到一个值, this value is determined by the Func-yield Control, so next will print from top to bottom.
Print (' First return value: ', res1)

Print (' = ' *100)
Res2=next (g)
Print (' Second return value: ', Res2)

The output is:
<generator object Func at 0x05597bd0>
First1
First2
First3
Return value for the first time: 1
===============================================================
Second1
Second2
Second3
Return value for the second time: 2


1. Generator Next value (for loop), for example 2:

For item in G: #g =iner (g) #item =next (g)
Pass #注意Next (g) Prints the result of the function body print only , and the yield pauses Pass,yield and continues the next loop.

Output Result:
First1
First2
First3
Second1
Second2
Second3
Third
Fourth


The actual yield value has been assigned to Item=next (g), item, but not printed above
For item in G:
Print (item)
First1
First2
First3
1
Second1
Second2
Second3
2
Third
3
Fourth

2. Customize the Range function model (for example: My_Range)
def my_range (start,stop,step=1):
While start < stop:
Yield start
Start+=step

Obj=my_range (1,7,2) #顾头不顾尾只能从1, value in 2,3,4,5,6
Print (Next (obj)) #1
Print (Next (obj)) #3
Print (Next (obj)) #5
Print (Next (obj)) #报错StopIteration

3. Ternary expression (return value if conditional if condition is not established when condition is established )
x=10
Y=20
res = x if x > Else y
Print (RES)


4. List generation: ( value placed on the left of the For Loop )) (for a basket of eggs)

#原始取值
L=[]
For I in Range (1,11):
L.append (i)
Print (L)

Improvements to:
L=[i for I in Range (1,11)]
Print (L) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Get a set of lists that account for large memory space

For example 1:
names=[' Alex ', ' wxx ', ' LXX ']
Names=[name+ ' SB ' for name in Names]
Print (names) #[' alexsb ', ' wxxsb ', ' LXXSB ']


5. Generator expression: (to a chicken)
# relative column generation save space, just start doing nothing,T itself is an iterator , need to take a value
t=(i-i in range (100000000))
Print (t) #<generator object <genexpr> at 0x05057bd0> get a generator that does not occupy memory space
Print (Next (t)) #0
Print (Next (t)) #1
Print (Next (t)) #2


6. Dictionary-generated: ()
keys=[' name ', ' age ', ' sex '
values=[' Egon ', ' Male ']
Res=zip (keys,values)
Print (list (res)) #[(' name ', ' Egon '), (' Age ', '), (' Sex ', ' male ')]
Way One
d={}
For k,v in Zip (keys,values):
D[k]=v
Print (d) #{' name ': ' Egon ', ' age ': +, ' sex ': ' Male '}

Way Two
D={k:v for k,v in Zip (keys,values)}
Print (d) #{' name ': ' Egon ', ' age ': +, ' sex ': ' Male '}


7.zip () Zipper function:
s= ' Hello '
l=[1,2,3,]
Res=zip (s,l)
Print (list (res)) #[(' H ', 1), (' E ', 2), (' L ', 3)]

8.max function (the longest value of the number of digits Len)
Scenario 1:
With open (' A.txt ', encoding= ' utf-8 ') as F:
Nums=[len (line) to line in F] # "" Nums the values are all stored in the list
Print (max (nums)) #返回值32
Print (max (nums)) #在任何地方取都OK #返回值32
# scenario 2:
With open (' A.txt ', encoding= ' utf-8 ') as F:
nums= (len Line) is #如果 (), Nums is an iterator object, and every time it is taken there is no
Print (max (nums)) #返回值32
Print (max (nums)) #max () arg is an empty sequence above has been the maximum value, then the hint is empty

Python builder, ternary expression, list-generated, dictionary-generated, generator-expression

Related Article

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.