Python Basics (9) Ternary expressions, list parsing, generator expressions

Source: Internet
Author: User

one or three meta-expressionsThe ternary operation is the abbreviation for a simple conditional statement. # if Condition statement
If x > F:    print (x) Else:    

  

# condition set left, not set right
x if x > y else y    # ternary expression
The ternary operation format for Python is as follows:
result= value 1 if x<y else value 2

  

# Assign value 1 to the result variable if the condition is true, otherwise assign value 2 to the result variable Second, list analysisList parsing: Use ternary expressions to write the results to a list, that is, list parsing using list generation, you can write very concise code.

What if you want to generate [1x1, 2x2, 3x3, ..., 10x10]? Method One is the loop:
#方法一L = []for x in range (1, one):    l.append (x * x) #结果L [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # method Two: list resolution [x * x for X in Range (1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
When writing list generation, put the element x * x to the front, followed by the For loop, you can create a list, very useful, write a few more times, you will soon be familiar with this syntax. The For loop can also be followed by an if judgment:
[x * x for x in range (1, one) if x% 2 = = 0] [4, 16, 36, 64, 100]

You can also use a two-layer loop to generate a full array:

[M+n for M in ' ABC ' for n in ' XYZ '] [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']
Three-and three-storey loops are rarely used. The For loop can also use two or more variables at the same time, such as Dict's items () to iterate key and value at the same time:
D = {'x':'A','y':'B','Z':'C' } forKvinchD.items ():PrintK'=', v) y=Bx=Az= C
As a result, list generators can also use two variables to generate lists:
D = {'x':'A','y':'B','Z':'C'}[k+'='-0 forKvinchD.items ()] ['y=b','X=a','Z=c']
List Parsing Instances
#遍历
s='hello'l=[] for in s: res= I.upper () l.append (res)print(l)
#####################################
#列表解析: s= ' Hello 'res=[i.upper () for I in s]print (res) 

Requirements: List 1~10 Square of all numbers####################################################1, common method:>>> L = []>>> forIinchRange (1,11):... L.append (i**2)...>>>Printl[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]####################################################2, List parsing>>>l = [i**2 forIinchRange (1,11)]>>>Printl[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Requirements: List 1~The square of a number greater than or equal to 4 in 10####################################################1, common method:>>> L = []>>> forIinchRange (1,11):...     ifI >= 4:... L.append (i(*p)...>>>Printl[16, 25, 36, 49, 64, 81, 100]####################################################2, List parsing>>>l = [i**2 forIinchRange (1,11)ifI >= 4 ]>>>Printl[16, 25, 36, 49, 64, 81, 100]

Requirements: List"/var/log"All the'. Log'End of File##################################################1, Common methods>>>ImportOS>>>file = []>>> forFileinchOs.listdir ('/var/log'):...     ifFile.endswith ('. Log'): .... file.append (file) ...>>>Printfile['Anaconda.ifcfg.log','Xorg.0.log','Anaconda.storage.log','Xorg.9.log','Yum.log','Anaconda.log','Dracut.log','Pm-powersave.log','Anaconda.yum.log','Wpa_supplicant.log','Boot.log','Spice-vdagent.log','Anaconda.program.log']##################################################2. List parsing>>>ImportOS>>> file = [file forFileinchOs.listdir ('/var/log')ifFile.endswith ('. Log') ]>>>Printfile['Anaconda.ifcfg.log','Xorg.0.log','Anaconda.storage.log','Xorg.9.log','Yum.log','Anaconda.log','Dracut.log','Pm-powersave.log','Anaconda.yum.log','Wpa_supplicant.log','Boot.log','Spice-vdagent.log','Anaconda.program.log']

Summaryby using the List Builder, you can quickly generate a list that can derive another list from a list, while the code is very concise. third, generator expression
egg_list=['Egg%s'%i forIinchRange (10)]#List Parsing #############################################Laomuji=('Egg%s'%i forIinchRange (10))#Builder ExpressionPrint(Laomuji)Print(Next (Laomuji))#Next is essentially calling __next__ .Print(Laomuji.__next__())Print(Next (Laomuji))

Summary: 1. The [] Conversion of the list parsing [] to () is the generator expression 2. List parsing and builder expressions are a convenient way to program, except that the generator expression saves memory 3.Python not only uses the iterator protocol, but also makes the for loop more generic. Most built-in functions also access objects using an iterator protocol. For example, the SUM function is a python built-in function that accesses an object using an iterator protocol, and the generator implements an iterator protocol, so we can calculate the sum of a series of values directly:SUM (x * * 2 for X in Xrange (4))Instead of superfluous first construct a list: sum ([x * * 2 for X in Xrange (4)])

Python Basics (9) Ternary expressions, list parsing, generator expressions

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.