# 1.列表推导式 a = [x**2 for x in range(5)] a # [0, 1, 4, 9, 16] b = [x for x in a if x % 2 == 0] b # [0, 4, 16] ‘‘‘ 等价于下面的for循环 b = [] for x in a: if x % 2 == 0: b.append(x) ‘‘‘ # 2.集合推导式 # 与列表推导式用法一致 L=[‘java‘,‘c++‘,‘python‘,‘ruby‘,‘php‘,None] unique_length = {len(x) for x in L if x is not None} unique_length # {3, 4, 6} # 3.字典推导式 dict1 = {a:b for a, b in zip(range(5),L) if len(b)>3} dict1 # {0: ‘java‘, 2: ‘python‘, 3: ‘ruby‘} # 4.嵌套的列表推导式 matrix = [[1,2,3],[4,5,6],[7,8,9]] L1 = [x for l in matrix for x in l ] L1 # [1, 2, 3, 4, 5, 6, 7, 8, 9] L2 = [[l[i] for l in matrix ] for i in range(len(matrix[0]))] L2 # [[1, 4, 7], [2, 5, 8], [3, 6, 9]] # 实现矩阵转置
原文:https://www.cnblogs.com/babysteps/p/python_note_8.html