怎样在python中输出多个数组元素
如果要输出多个列表元素,实际上是列表的分片或者说是切片。
以下代码运行通过:12list = ['a', 'b', 'mpilgrim', 'z', 'example']print('\n', list[0:3])
运行效果:
1.python输出一维矩阵或numpy数组中的非0元素
import numpy as np
a = np.mat([[0,1,0,1,2,3,4,0]])
b = np.array([0,1,0,1,2,3,4,0])print a[a>0] # []里面是不等式成立的情况print b[(b>0) & (b < 3)]12345
输出结果:
[[1 1 2 3 4]]
[1 1 2]
2.但是列表不行:
import numpy as np
a = np.mat([[0,1,0,1,2,3,4,0]])
b = a.tolist() #把矩阵转换为列表print a[a>0]print b#print b[b>0] #这一句是错误的123456
输出结果:
[[1 1 2 3 4]]
[[0, 1, 0, 1, 2, 3, 4, 0]]
3.另外,直接对二维矩阵(numpy数组)输出也是不行的:
import numpy as np
a = np.mat([[0,1,0,1,2,3,4,0],[1,2,0,1,0]])
b = np.array([[0,1,0,1,2,3,4,0],[1,2,0,1,0]])print a[a>0]print b[b>0]12345
输出结果:
[[[0, 1, 0, 1, 2, 3, 4, 0] [1, 2, 0, 1, 0]]]
[[0, 1, 0, 1, 2, 3, 4, 0] [1, 2, 0, 1, 0]]
print a[0],a[2]