01 示例函数
1.1 代码及结果
import matplotlib.pyplot as plt import matplotlib.colors import numpy as np from mpl_toolkits.mplot3d import Axes3D def midpoints(x): sl = () for i in range(x.ndim): x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0 sl += np.index_exp[:] return x # prepare some coordinates, and attach rgb values to each r, theta, z = np.mgrid[0:1:11j, 0:np.pi*2:25j, -0.5:0.5:11j] x = r*np.cos(theta) y = r*np.sin(theta) rc, thetac, zc = midpoints(r), midpoints(theta), midpoints(z) # define a wobbly torus about [0.7, *, 0] sphere = (rc - 0.7)**2 + (zc + 0.2*np.cos(thetac*2))**2 < 0.2**2 # combine the color components hsv = np.zeros(sphere.shape + (3,)) hsv[..., 0] = thetac / (np.pi*2) hsv[..., 1] = rc hsv[..., 2] = zc + 0.5 colors = matplotlib.colors.hsv_to_rgb(hsv) # and plot everything fig = plt.figure() ax = fig.gca(projection='3d') ax.voxels(x, y, z, sphere, facecolors=colors, edgecolors=np.clip(2*colors - 0.5, 0, 1), # brighter linewidth=0.5) plt.show()
绘制的3D图像
1.2 Python函数
在代码中,包括有以下几个函数值得进一步的探究,以备之后学习和应用。
- np.index_exp:产生array 的索引元组;
- shape() + (3,) : 对于一个元组增加维度;
- 省略号: 自适应数组索引;
语法糖 (Syntactic Sugar)是为了方便编程人员使用的变化的语法,它并不对原来的功能产生任何影响。
比如:
- a[i] : *(a+i)
- a[i][j] : (a+icol +j)
02 数组索引
2.1 省略号
利用省略号,可以自适应匹配前面省略的数组索引。
下面定义了一个3D数字:x。
import sys,os,math,time import matplotlib.pyplot as plt from numpy import * x = array([[[1],[2],[3]], [[4],[5],[6]]]) print("x: {}".format(x), "x.shape: {}".format(x.shape))
x: [[[1] [2] [3]] [[4] [5] [6]]] x.shape: (2, 3, 1)
下面通过省略号访问x,可以看到它与前面补齐索引是相同的效果。
x1 = x[...,0] x2 = x[:,:,0] print("x1: {}".format(x1),"x2: {}".format(x2))
x1.shape: (2, 1, 3, 1) x2.shape: (2, 1, 3, 1)
2.2 扩增数组维度
扩增数组维度,可以使用一下两个等效的语法来完成。
x1 = x[:,None,:,:] x2 = x[:,newaxis,:,:] print("x1.shape: {}".format(x1.shape), "x2.shape: {}".format(x2.shape))
x1.shape: (2, 1, 3, 1) x2.shape: (2, 1, 3, 1)
2.3 元组相加
元组可以通过“+”串联在一起:
a = (1,2,3) b = (1,) print(a+b)
(1, 2, 3, 1)
实际上对于列表也是可以的:
a = [1,2,3] b = [1] print(a+b)
[1, 2, 3, 1]
但是list 与 tuple 不能够叠加:
a = [1,2,3] b = (1,) print(a+b)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_164/1922126339.py in5 a = [1,2,3] 6 b = (1,) ----> 7 printt(a+b) TypeError: can only concatenate list (not "tuple") to list
2.4 一维变二维
import numpy a = array([1,2,3,4]) b = array([5,6,7,8]) d = numpy.r_[a,b] print("d: {}".format(d))
d: [1 2 3 4 5 6 7 8]
import numpy a = array([1,2,3,4]) b = array([5,6,7,8]) d = numpy.c_[a,b] print("d: {}".format(d))
d: [[1 5]
[2 6]
[3 7]
[4 8]]
总结
在Python中还存在一些有趣的 Syntatic Sugar (语法糖果),在编程的时候可以进一步简化编程的效率。
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!