
Practice2:
1. 从1到10中随机选取10个数,大于3和小于8的取负数。
a = np.random.randint(1,11,10)print(a)for i in range(10):if a[i]>3 and a[i]<8:a[i]=-a[i]print(a)
输出结果:
[2 6 1 7 7 1 4 8 9 4]
[ 2 -6 1 -7 -7 1 -4 8 9 -4]
2. 在数组[1, 2, 3, 4, 5]中相邻两个数字中间插入1个0。
a = [1,2,3,4,5]b = np.zeros(9,dtype=int)b[::2]=a #定义b数组,用替换的方式作为插入b
输出结果:
array([1, 0, 2, 0, 3, 0, 4, 0, 5])
3. 把一个10*2的随机生成的笛卡尔坐标转换成极坐标。
import numpy as np#笛卡尔坐标a = np.random.rand(10,2)print(a)#极坐标x = a[:,0]y = a[:,1]r = np.sqrt(x**2+y**2) #距原点距离R = np.arctan(y/x) #弧度b = np.vstack((r,R))print(b)b.T
输出结果:
[[0.13326275 0.18704839]
[0.23688548 0.36797625]
[0.03135753 0.14299739]
[0.40299371 0.13383203]
[0.23959877 0.09104552]
[0.61510793 0.13311254]
[0.12006293 0.35719826]
[0.07253187 0.83783839]
[0.20611959 0.83641382]
[0.46108641 0.17644776]]
[[0.22966511 0.43763142 0.14639518 0.42463507 0.25631398 0.62934626
0.37683644 0.84097208 0.86143681 0.49369473]
[0.95176301 0.99882585 1.35492579 0.32063526 0.36313965 0.21311886
1.24653623 1.48444138 1.32917808 0.36548528]]
array([[0.22966511, 0.95176301],
[0.43763142, 0.99882585],
[0.14639518, 1.35492579],
[0.42463507, 0.32063526],
[0.25631398, 0.36313965],
[0.62934626, 0.21311886],
[0.37683644, 1.24653623],
[0.84097208, 1.48444138],
[0.86143681, 1.32917808],
[0.49369473, 0.36548528]])
4. 获取数组 a 和 b 中的共同项(索引位置相同,值也相同)。
a = np.array([1,2,3,2,3,4,3,4,5,6]),
b = np.array([7,2,10,2,7,4,9,4,9,8])
a = np.array([1,2,3,2,3,4,3,4,5,6])b = np.array([7,2,10,2,7,4,9,4,9,8])c = a-ba[c==0]
输出结果:
array([2, 2, 4, 4])
