PYTHON-列表解析


#first option
square0=[]
for value in range(1,11):
	square0.append(value**2)
print(square0)
#second option
square = [value**2 for value in range(1,11)]
print(square)
#compared first option and second option,we can easily find the simple way is second option

代码如上,运行结果如下:

列表解析是第二种创建数字列表的一种简便方法

使用这种语法,指定一个描述性的列表名,例如上面的square;然后指定一个左方括号,并定义一个表达式,用于生成你要存储到列表的值。

在上面的例子中,表达式为value**2,用来计算平方值。接下来就是,编写for循环,用于给表达式提供值,类似数学中自变量,value**2类似函数表达式,自变量的不断改变,随后因变量对应的值写入列表square中,然后在加上由方括号。列表的完整性。range(1,11)产生1-10这10个数。

                                                                                                                                                                                                      20180519

猜你喜欢

转载自blog.csdn.net/shuipengpeng/article/details/80370312