python numpy matrix slice and string slice

  • Create 4 matrices of 6*6, respectively, the matrix values ​​are all 0, the matrix values ​​are all 1, the matrix values ​​are all specified values, and the matrix values ​​are random;

    import numpy as np
    x1 = np.zeros((6,6))
    x2 = np.ones((6,6))
    x3 = np.full((6,6),255)#可以将255换成别的数字
    x4 = np.random.rand(6,6)
    print(x1)
    print(x2)
    print(x3)
    print(x4)

    operation result:
    write picture description here

  • Read the first and fourth numbers of the second and third rows of matrix x4:

x4 = np.random.rand(6,6)
print(x4[2:4,1:5])
  • Read the first and fourth numbers of all rows of matrix x4:
x4 = np.random.rand(6,6)
print(x4[:,1:5])
  • Read the 0th and 3rd numbers of all columns of matrix x4
x4 = np.random.rand(6,6)
print(x4[0:4,:]) #包括下标为0的数字,不包括下标为4的数字
  • print matrix x4 from back to front
x5 = np.array([(1,2,3),(5,6,8)])
print(x5)
print(x5[::,::-1]) #-1表示步长,也可以设置别的数字
print(x5[::-1])

write picture description here

  • Set step size to 2
x5 = np.array([(1,2,3),(5,6,8)])
print(x5[::,::2]) #步长为2

write picture description here

  • Take only the column labeled 2
x5 = np.array([(1,2,3),(5,6,8)])
print(x5)
print(x5[:,2]) #逗号前一个冒号表示所有行

write picture description here


Added:
String slices are very similar to matrix slices:

s = 'abcdefgh'
print(s)
print(s[::-1]) #-1表示步长
print(s[::2])
print(s[0:5])#下标为0的计算入内,下标为5的不计算入内

Output:
abcdefgh
hgfedcba
aceg
abcde

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325171817&siteId=291194637