List comprehensions
# list generation: Python's built-in, very simple but powerful build that can be used to create lists.
# Generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] can be used with list (range (1, one)): >>> list (range (1, one)) [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]
# generate [1x1, 2x2, 3x3, ..., 10x10]>>> L = [] for in range (1, one): .... * x) ... >>> l[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#because the loop is too cumbersome, the list generation can generate a single line of statements instead of looping the above list:>>> [x * x forXinchRange (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 the list. #and the For loop can be followed by an if judgment so that we can filter out only the even squares:>>> [x * x forXinchRange (1, 11)ifX% 2 = =0] [4, 16, 36, 64, 100]
#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']
#三层和三层以上的循环就很少用到了.
#using list generation, you can list all the file and directory names in the current directory, which can be implemented in one line of code:>>> [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']#A For loop can actually use two or more variables at the same time, such as Dict's items () to iterate over both key and value:>>> 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 +'='+ V 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']
Python: List-generated