小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
学习keras时照着弗朗索瓦的教程敲代码,然后就遇见了如题的一串表达。
尽管很容易就能看出这是Python的列表推导式,但我着实还是花了好一会儿才彻底看懂它的逻辑,此篇文章则为其记录。
什么是列表推导式(List comprehensions)
Python3官方文档:docs.python.org/3/tutorial/…
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
列表推导式提供了一种创建列表的简明方式。常见的应用是创建新的列表,新列表中每个元素都是对另一个序列或可迭代对象中的每个成员操作的结果,此外也可以用来创建一个满足某个条件的元素的子序列。
示例分析
-
最基本的一种列表推导式形式如下
>>> newList = [lambda:x for x in List]例如:
>>> squares = [x**2 for x in range(10)] #输出为0~9的平方 -
列表推导式可以循环嵌套,不仅是
for循环,甚至还可以后接if条件语句。其结果是一个新的列表,该列表是在其后面的for和if子句的上下文中对表达式进行判断后产生的。例如:>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]其等价于:
>>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] -
基于第2点的认知,我们现在介绍
嵌套列表推导式(Nested List Comprehensions)列表推导式中的初始表达式可以是任何任意的表达式,甚至可以包括后续的列表推导式
例如:
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] #转置该矩阵 >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]该代码等价于:
>>> transposed = [] >>> for i in range(4): ... # the following 3 lines implement the nested listcomp ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] -
基于以上认知,我们现在可以来理解题目代码了
np.mean(x[i] for x in matrix) for i in range(num)即等价于:
>>> mean_array = [] for i in range(4): temp = 0 for x in matrix: temp += x[i] x_mean = temp/3 mean_array.append(x_mean)即该代码的意义为,以列(axis=0)为标准,求取矩阵每列的均值。