# 列表——理解

``````>>> col2 = [row[1] for row in M] # 收集列中的项
2
>>> col2
[2, 5, 8]
>>> M # 矩阵没变
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]``````

``````>>> [row[1] + 1 for row in M] # 给第2列的每项都加1
[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']``````

``````>>> list(range(4)) # 0..3 (在 3.X 中需要 list())
[0, 1, 2, 3]
>>> list(range(−6, 7, 2)) # −6 到 +6 步进 2 (在 3.X 中需要 list())
[−6, −4, −2, 0, 2, 4, 6]
>>> [[x ** 2, x ** 3] for x in range(4)] # 多个值, "if" 过滤
[[0, 0], [1, 1], [4, 8], [9, 27]]
>>> [[x, x / 2, x * 2] for x in range(−6, 7, 2) if x > 0]
[[2, 1, 4], [4, 2, 8], [6, 3, 12]]``````

``````>>> G = (sum(row) for row in M) # 创建一个行的和的生成器
>>> next(G) # 这里不需要 iter(G)
6
>>> next(G) # 运行迭代协议 next()
15
>>> next(G)
24``````

``````>>> list(map(sum, M)) # 对M中的项映射 sum 函数
[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}``````

``````>>> [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'} # 字典的键是唯一不重复的
{'p': 112, 'a': 97, 's': 115, 'm': 109}
>>> (ord(x) for x in 'spaam') # 值的生成器
<generator object <genexpr> at 0x000000000254DAB0>``````