學習Python的人都知道數組是最常用的的數據類型,為了保證程序的正確性,需要調試程序。
因此,需要在程序中控制臺中打印數組的全部元素,如果數組的容量較小,例如 只含有10個元素,采用print命令或print函數可以答應出數組中的每個元素;
如果數組的容量過大,只能打印出數組的部分元素,打印結果只包含開始部分元素和結尾部分元素,中間元素省略。省略的部分不利于程序的調試;
因此,為了方便調試程序,需要將數組中的元素全部打印出來。
1. 少量元素情況
#打印數組中的元素import numpy as npa = np.array(6)print a
程序結果為:
[0 1 2 3 4 5]
2. 大量元素情況
可以采用 set_printoptions(threshold='nan')
import numpy as npnp.set_printoptions(threshold=np.NaN)print np.arange(100)print np.arange(100).reshape(10, 10)
結果為:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
當array里面的存放的數據維度過大時,在控制臺會出現不能將array完全輸出的情況,中間部分的結果會用省略號打印出來。這時就需要用到numpy里面的set_printoptions()方法
我們來看一下 set_printoptions 方法的簡單說明
set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None)
precision:輸出結果保留精度的位數
threshold:array數量的個數在小于threshold的時候不會被折疊
edgeitems:在array已經被折疊后,開頭和結尾都會顯示edgeitems個數
formatter:這個很有意思,像python3里面str.format(),就是可以對你的輸出進行自定義的格式化
舉例:
precision:
np.set_printoptions(precision=4)print(np.array([1.23456789]))>> [ 1.2346] # 最后進位了
threshold:
np.set_printoptions(threshold=10)print(np.arange(1, 11, 1)) # np.arange(1, 11, 1)生成出來是[1-10],10個數>> [ 1 2 3 4 5 6 7 8 9 10]np.set_printoptions(threshold=9)print(np.arange(1, 11, 1))>> [ 1 2 3 ..., 8 9 10]
新聞熱點
疑難解答