使用numpy.diag()可以很方便的求出这个数组
函数结构
diag(v, k=0)
参数说明
例子
#提取对角线元素
In [6]: c = np.random.randint(1,10, (3,3))
In [7]: c
Out[7]:
array([[7, 1, 9],
[2, 8, 5],
[2, 6, 2]])
In [8]: np.diag(c)
Out[8]: array([7, 8, 2])
#提取对角线元素 添加偏移量k, 这样对偏移量就很好理解了
In [21]: c = np.random.randint(1,10, (3,3))
In [22]: c
Out[22]:
array([[7, 8, 6],
[3, 2, 6],
[4, 9, 8]])
In [23]: np.diag(c, -1)
Out[23]: array([3, 9])
#如果不是方阵,依然是对角线,多出来的列不考虑
In [24]: c = np.random.randint(1,10, (2,3))
In [26]: c
Out[26]:
array([[4, 2, 4],
[9, 6, 7]])
In [25]: np.diag(c)
Out[25]: array([4, 6])
#使用一维数组创建对角阵
In [27]: a = np.random.randint(1, 10, 3)
In [28]: a
Out[28]: array([2, 7, 7])
In [29]: np.diag(a)
Out[29]:
array([[2, 0, 0],
[0, 7, 0],
[0, 0, 7]])
#创建对角矩阵 并传入偏移量, 其实就是上面提取对角线元素的逆过程
In [30]: a = np.random.randint(1, 10, 3)
In [31]: a
Out[31]: array([3, 7, 5])
In [32]: np.diag(a, -1)
Out[32]:
array([[0, 0, 0, 0],
[3, 0, 0, 0],
[0, 7, 0, 0],
[0, 0, 5, 0]])
所以,题目的解答可以这样写:
In [82]: c = np.diag(np.arange(1,5), k=-1)
In [83]: c
Out[83]:
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0]])
数组切片的综合应用,关键在于两种不同的行交替出现,找到这两种规律就好了
In [40]: a = np.zeros((10, 10), dtype=np.int)
In [41]: a[0::2, 1::2] = 1
In [42]: a[1::2, 0::2] = 1
In [43]: a
Out[43]:
array([[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]])
In [96]: a = np.arange(11)
In [97]: a[(a>1) & (a<=9)] *= -1
In [98]: a
Out[98]: array([ 0, 1, -2, -3, -4, -5, -6, -7, -8, -9, 10])
In [99]: a = np.arange(11)
In [100]: b = [-1*i if(i>1 and i<=9) else i for i in a]
In [101]: b
Out[101]: [0, 1, -2, -3, -4, -5, -6, -7, -8, -9, 10]
集合运算
In [108]: np.intersect1d(a,b)
Out[108]: array([4, 7])
#注意这个intersect后面是数字1