python list comprehension

m=[[1,2,3],[4,5,6],[7,8,9]]

col2=[row[ 1 ] for row in m]   #Get a list consisting of the value of the second element of each element of list m
 print (col2)
 print ([row[ 1 ]+ 1 for row in m])   # Get a list consisting of the value of the second element + 1 of each element of list m
 print ([row[ 1 ] for row in m if row[ 1 ]% 2 == 0 ])    #Get each element of list m The second element of the list of even values
 ​​print ([m[i][i] for i in [ 0 , 1 , 2]])    #Get a list of m[0,0],m[1,1],m[2,2] values
 ​​print ([c* 2 for c in 'spam' ])    #Get each word of spam A list of point values ​​after section*2

List comprehension syntax can also be used to create generators that produce the desired result
m=[[1,2,3],[4,5,6],[7,8,9]]

g=( sum (row) for row in m)
 print ( type (g))     #g is a generator, the content is the sum of the sub-elements of the three elements of m
 print ( next (g))     #m [0][0]+m[0][1]+m[0][2]=6
 print ( next (g))     #m[1][0]+m[1][1]+m[ 1][2]=6
 print ( next (g))     #m[2][0]+m[2][1]+m[2][2]=6
 print ( next (g))     #out of range , report exception
m=[[1,2,3],[4,5,6],[7,8,9]]

 
 
List comprehension syntax can be used to create collections
m=[[1,2,3],[4,5,6],[7,8,9]]
print({ sum (row) for row in m}) #Generate a set, the content is the sum of the sub-elements of the three elements of m
 
 
List comprehension syntax can be used to create dictionaries
m=[[1,2,3],[4,5,6],[7,8,9]]
print({i: sum (m[i]) for i in range ( 3 )}) #Generate a dictionary {0: 6, 1: 15, 2: 24}
 
 
 
 
Lists, sets, dictionaries can all be created using parsing
print ([ ord (x) for x in 'spaam'])    #[115, 112, 97, 97, 109]
 print ({ ord (x) for x in 'spaam'})    #{112, 97, 115, 109} The set will be deduplicated
 print ({x: ord (x) for x in 'spaam'})   #{'s': 115, 'p': 112, 'a': 97, 'm': 109} The set Key-value repeated update operation

 
 
 
 
 
 
 
 
Extended list comprehension syntax
lines=[line for line in open ( 'e:/kangyujiao/test.txt' ) if line[ 0 ]== 'b' ]   #The first character of each line is the return of b
l=[x+y for x in 'abc' for y in 'lmn']    #嵌套循环l=['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326002060&siteId=291194637