我是 Python 新手,遇到了以下查询。谁能解释以下原因:
[ n**2 for n in range(1, 6)]
给出:
[1, 4, 9, 16, 25]
在解释器中将其分解为可管理的块:
>>> range(1, 6)
[1, 2, 3, 4, 5]
>>> 2 ** 2 # `x ** 2` means `x * x`
4
>>> 3 ** 2
9
>>> for n in range(1, 6):
... print n
1
2
3
4
5
>>> for n in range(1, 6):
... print n ** 2
1
4
9
16
25
>>> [n ** 2 for n in range(1, 6)]
[1, 4, 9, 16, 25]
它被称为列表推导。发生的情况类似于以下内容:
results = []
for n in range(1,6):
results.append(n**2)
因此,它遍历包含值的列表[0, 1, 2, 3, 4, 5]
并对每个值求平方。然后将平方的结果添加到results
列表中,并返回您看到的结果(相当于0**2, 1**2, 2**2
等,其中的**2
意思是“提高到二次方”)。
这种结构(使用基于其他标准的值填充列表)在 Python 中很常见,因此列表推导式提供了一种速记语法来允许您这样做。
所以这是一个列表理解。
如果你把它分成 3 个部分;由单词分隔:'for' 和 'in' ..
例如。
[ 1 比 2 合 3 ]
可能向后阅读它是最简单的:
第 1 部分和第 2 部分运行多次,第 3 部分给我们的列表中的每个项目运行一次。第 1 部分反复运行的输出是整个操作的输出。
所以在你的例子中:
所以等效的代码是:
result = []
for n in range(1, 6):
result.append(n**2)
最后把它全部打破:
input = [1, 2, 3, 4, 5]
output = []
v = input[0] # value is 1
o = v**2 # 1 to the power of two is 1
output.append(o)
v = input[1] # value is 2
o = v**2 # 2 to the power of two = (2*2) = 4
output.append(o)
v = input[2] # value is 3
o = v**2 # 3 to the power of two is = (3*3) = 9
output.append(o)
v = input[3] # value is 4
o = v**2 # 4 to the power of two is = (4*4) = 16
output.append(o)
v = input[4] # value is 5
o = v**2 # 5 to the power of two is = (5*5) = 25
output.append(o)