The list generation, which is the comprehensions, is a very simple and powerful build of Python built-in that can be used to create lists.
For example, to generate a list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
you can use list(range(1, 11))
:
>>> list (range (1, one)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But what if you want to build [1x1, 2x2, 3x3, ..., 10x10]
? Method One is the loop:
>>> L = [] for in range (1, one): ... . * x) ... >>> l[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
But the loop is too cumbersome, and the list generation can use a line of statements instead of loops to generate the list above:
for in range (1, one) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
def f (N): return n*n*na for in range ()print(a)
Build Result:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
When writing list generation, put the elements to be generated in x * x
front, followed by the for
loop, you can create a list, very useful, write a few more times, you can quickly become familiar with this syntax.
The For loop can also be followed by an if judgment so that we can filter out only the even squares:
for inch if x% 2 = = 0][4, 16, 36, 64, 100]
def f (N): return n*n*nafor inif x%2==0)print(a)
Results:
[0, 8, 64, 216, 512]
You can also use a two-layer loop to generate a full array:
>>> [M + N forMinch 'ABC' forNinch 'XYZ']['AX','AY','AZ','BX',' by','BZ','CX','CY','CZ']
Three-and three-storey loops are rarely used.
Using a list-generated formula, you can write very concise code. For example, listing all the file and directory names in the current directory can be implemented in one line of code:
>>>ImportOs#Import the OS module, the concept of the module>>> [D forDinchOs.listdir ('.')]#Os.listdir can list files and directories['. EMACS.D','. SSH','. Trash','ADLM','Applications','Desktop','Documents','Downloads','Library','Movies','Music','Pictures',' Public','VirtualBox VMs','Workspace','XCode']
for
Loops can actually use two or more variables at the same time, such as dict
the items()
ability 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']
Finally, all the strings in a list are converted to lowercase:
>>> L = ['Hello',' World','IBM','Apple']>>> [S.lower () forSinchL] ['Hello',' World','IBM','Apple']
Practice:
If the list contains both a string and an integer, there is no method for the non-string type lower()
. Use list generation to keep only string type data and make it lowercase ['Hello', 'World', ' Apple', None]
>>> L = ['Hello',' World', 18,'Apple', None]>>> [S.lower () forSinchL] Traceback (most recent): File"<stdin>", Line 1,inch<module>File"<stdin>", Line 1,inch<listcomp>Attributeerror:'int'object has no attribute'Lower'
Use the built-in isinstance
function to determine if a variable is a string:
' ABC '>>> y = 123>>> isinstance (x, str) True>>> isinstance (y, str) False
Use list generation to if
ensure that list generation performs correctly by adding statements:
#-*-coding:utf-8-*-L1 = ['Hello',' World', 18,'Apple', None]#def low_str (s):#if Isinstance (s,str):#return S.lower ()#Else:#return SL2= [X.lower () forXinchL1ifisinstance (X,STR)]#Test:Print(L2)ifL2 = = ['Hello',' World','Apple']: Print('Test pass!')Else: Print('Test failed!')
Results:
['hello'World'Apple' ] Test pass!
#-*-coding:utf-8-*-L1 = ['Hello',' World', 18,'Apple', None]defLow_str (s):ifisinstance (S,STR):returnS.lower ()Else: returns L2= [Low_str (x) forXinchL1]#Test:Print(L2)
Results:
['hello'World'Apple' , None]
Python Getting Started 16th day __ List generation