學習Python的人都知道數組是最常用的的數據類型,為了保證程序的正確性,需要調試程序。
因此,需要在程序中控制臺中打印數組的全部元素,如果數組的容量較小,例如 只含有10個元素,采用print命令或print函數可以答應出數組中的每個元素;
如果數組的容量過大,只能打印出數組的部分元素,打印結果只包含開始部分元素和結尾部分元素,中間元素省略。省略的部分不利于程序的調試;
因此,為了方便調試程序,需要將數組中的元素全部打印出來。
1. 少量元素情況
#打印數組中的元素 import numpy as np a = np.array(6) print a
程序結果為:
[0 1 2 3 4 5]
2. 大量元素情況
可以采用 set_printoptions(threshold='nan')
import numpy as np
np.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]
edgeitems:
np.set_printoptions(threshold=5) print(np.arange(1, 11, 1)) >> [ 1 2 3 ..., 8 9 10] np.set_printoptions(threshold=5, edgeitems=4) print(np.arange(1, 11, 1)) >> [ 1 2 3 4 ..., 7 8 9 10]
formatter
np.set_printoptions(formatter={'all': lambda x: 'int: ' + str(-x)}) print(np.arange(1, 5, 1)) >> [int: -1 int: -2 int: -3 int: -4]
這個formatter是一個可調用的字典,'all'是其中一個key,表示里面的x可以包含所有type,還有其他key,具體可以在源碼里面查看最后如果只想在代碼中的某一部分使用自定義的printoptions,那么可以通過再次調用np.set_printoptions()這個方法來進行reset
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
