• 列表解析
  • list comprehension expression
>>> M=[[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> M[1]
[4, 5, 6]
>>> M[1][2]
6
>>> col2=[row[1] for row in M]
>>> col2
[2, 5, 8]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> 
>>> [row[1]+1 for row in M]
[3, 6, 9]
>>> [row[1] for row in M if row[1]%2==0]
[2, 8]

>>> diag=[M[i][i] for i in [0,1,2]]
>>> diag
[1, 5, 9]
>>> doubles=[c*2 for c in 'spam']
>>> doubles
['ss', 'pp', 'aa', 'mm']

>>> G=(sum(row) for row in M)
>>> next(G)
6
>>> next(G)
15
>>> next(G)
24


>>> list(map(sum,M))
[6, 15, 24]




复制代码

解析语法可以创建列表,集合,字典

>>> list(map(sum,M))
[6, 15, 24]
>>> {sum(row)for row in M}
{24, 6, 15}
>>> {i:sum(M[i]) for i in range(3)}
{0: 6, 1: 15, 2: 24}
>>> {i:M[i] for i in range(3)}
{0: [1, 2, 3], 1: [4, 5, 6], 2: [7, 8, 9]}

>>> [ord(x) for x in 'spaam']
[115, 112, 97, 97, 109]
>>> {ord(x) for x in 'spaam'}
{112, 97, 115, 109}
>>> {x:ord(x) for x in 'spaam'}
{'s': 115, 'p': 112, 'a': 97, 'm': 109}



复制代码

ord() function in Python Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord('€') (Euro sign) returns 8364