11、 import antigravity
import用于导入Python模块,antigravity是一个彩蛋性质的模块,导入之后会打开一个反重力漫画
12 、pip install numpy
在命令行中运行pip命令,可安装相应的模块,然后在Python中输入import numpy as np,就可以导入numpy包,并给与其np的标识,从而可用np.来调用numpy中的函数。
13 、x = np.arange(10)
生成一个自然序列,与range相似,但是np.arange得到的可进行运算的数组(array)。
>>> x = np.arange(10) >>> x array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
14、 x**2
只是演示一下,array可以使用运算符。
>>> x**2 array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81], dtype=int32)
15、 x.tolist()
将x从array转成list,由于列表(list)并不支持乘方运算,所以下面第二行代码报了错。
>>> x.tolist() [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> x.tolist()**2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
16-18、
>>> if len(x)==5:print(x) ... elif len(x)==10: print(x.tolist()+x) ... else: print(x[0]) ... [ 0 2 4 6 8 10 12 14 16 18]
len表示获取x的长度,python中通过==来判断二者是否相等。上式表示,如果x的长度等于5,则打印x;或者x的长度为10,则打印x.tolist()+x;如果x的长度为其他值,则打印x[0]。
由于x的长度是10,所以执行了第2行代码。而且python非常智能地按照array的规则计算了x.tolist()+x。这说明,当表达式中同时存在array和list的时候,python会自动将list转为array。
19-20、
>>> d = {"a":1,"b":2,"c":3} >>> d["a"] 1
d即为字典,可通过键值对的形式进行索引。案例中,"a","b","c"为键(key),1,2,3为值(value),通过key来索引value,非常便利。
如果觉得博客文章对您有帮助,异或土豪有钱任性,可以通过以下扫码向我捐助。也可以动动手指,帮我分享和传播。您的肯定,是我不懈努力的动力!感谢各位亲~