Python 构造列表
我是Python新手,遇到了以下查询。有人能解释为什么会出现以下情况:Python 构造列表,python,list,Python,List,我是Python新手,遇到了以下查询。有人能解释为什么会出现以下情况: [ n**2 for n in range(1, 6)] results = [] for n in range(1,6): results.append(n**2) 给出: [1, 4, 9, 16, 25] 它被称为a。发生的情况与以下类似: [ n**2 for n in range(1, 6)] results = [] for n in range(1,6): results.append(
[ n**2 for n in range(1, 6)]
results = []
for n in range(1,6):
results.append(n**2)
给出:
[1, 4, 9, 16, 25]
它被称为a。发生的情况与以下类似:
[ n**2 for n in range(1, 6)]
results = []
for n in range(1,6):
results.append(n**2)
因此,它将遍历包含值[0,1,2,3,4,5]
的列表,并对每个值进行平方运算。然后将平方运算的结果添加到结果
列表中,然后返回您看到的结果(这相当于0**2、1**2、2**2
等,其中**2
表示“提升到二次方”)
这种结构(使用基于其他一些标准的值填充列表)在Python中很常见,因此列表理解提供了一种简写语法,允许您这样做。在解释器中将其分解为可管理的块:
>>> range(1, 6)
[1, 2, 3, 4, 5]
这是一个很好的例子
如果你把它分成三部分;由“for”和“in”分开
例如
[3分之二为1]
也许倒读是最容易的:
- 3-这是整个操作的输入列表
- 2-这是大列表中的单个项目
- 1-这是对该项目执行的操作
在你的例子中:
- 3-生成一个列表:[1,2,3,4,5]--从第一个参数运行到第二个参数之前的
- 2-“n”表示该列表中的单个数字
- 1-生成n**2的新列表(n为2的幂)
因此,等效代码为:
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)
以下是一些有用的阅读:
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)