1.一般的列表推导式
>>> oho = [1,2,3,4,5]
>>> oho = [ i * 2 for i in oho]
>>> oho
[2, 4, 6, 8, 10]
从程序的执行效率来说,列表推导式的运行效率比普通的循坏要快一倍多,主要是因为列表推导式是以更快的C 语言的速度来运行的。
二维列表:>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> diag = [matrix[i][i] for i in range(len(matrix))]
>>> diag
[1, 5, 9]
matrix[i][i]下标索引值
2.进阶版的列表推导式,可以加上条件判断
>>> words = ['great','billin','fantastic','brlliant']
>>> fwords = [w for w in words if w[0] == 'f']
>>> fwords
['fantastic']
3.列表推导式,更为复杂的嵌套列表
[expression for target1 in iterable1
for target2 in iterable2
for targetN in iterableN]
matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> flatten = [col for row in matrix for col in row]
>>> flatten
[1, 2, 3, 4, 5, 6, 7, 8, 9]
#下方是平常的for循环语句
>>> for raw in matrix:
for col in raw:
flatten.append(col)
>>> flatten
[1, 2, 3, 4, 5, 6, 7, 8, 9]
另外一种,for循环 + if 判断
[expression for target1 in iterable1 if condition1
for target2 in iterable2 if condition2
for targetN in iterable2 if conditionN]
>>> [[x,y] for x in range(10) if x%2 == 0 for y in range(10) if y%3 == 0]
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]
#下方是平常的for循环语句+if条件判断语句
>>> _=[] #空列表
>>> for x in range(10):
if x % 2 == 0:
for y in range(10):
if y % 3==0:
_.append([x,y])