Python打印輸出數(shù)組中全部元素
學習Python的人都知道數(shù)組是最常用的的數(shù)據(jù)類型,為了保證程序的正確性,需要調(diào)試程序。
因此,需要在程序中控制臺中打印數(shù)組的全部元素,如果數(shù)組的容量較小,例如 只含有10個元素,采用print命令或print函數(shù)可以答應出數(shù)組中的每個元素;
如果數(shù)組的容量過大,只能打印出數(shù)組的部分元素,打印結果只包含開始部分元素和結尾部分元素,中間元素省略。省略的部分不利于程序的調(diào)試;
因此,為了方便調(diào)試程序,需要將數(shù)組中的元素全部打印出來。
1. 少量元素情況
#打印數(shù)組中的元素 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里面的存放的數(shù)據(jù)維度過大時,在控制臺會出現(xiàn)不能將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:輸出結果保留精度的位數(shù)
threshold:array數(shù)量的個數(shù)在小于threshold的時候不會被折疊
edgeitems:在array已經(jīng)被折疊后,開頭和結尾都會顯示edgeitems個數(shù)
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個數(shù) >> [ 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是一個可調(diào)用的字典,'all'是其中一個key,表示里面的x可以包含所有type,還有其他key,具體可以在源碼里面查看最后如果只想在代碼中的某一部分使用自定義的printoptions,那么可以通過再次調(diào)用np.set_printoptions()這個方法來進行reset
相關文章
python正則表達式中匹配次數(shù)與貪心問題詳解(+??*)
正則表達式是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配,下面這篇文章主要給大家介紹了關于python正則表達式中匹配次數(shù)與貪心問題(+??*)的相關資料,需要的朋友可以參考下2022-10-10Python自動化爬取天眼查數(shù)據(jù)的實現(xiàn)
本文將結合實例代碼,介紹Python自動化爬取天眼查數(shù)據(jù)的實現(xiàn),對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-06-06scrapy數(shù)據(jù)存儲在mysql數(shù)據(jù)庫的兩種方式(同步和異步)
這篇文章主要介紹了scrapy數(shù)據(jù)存儲在mysql數(shù)據(jù)庫的兩種方式(同步和異步),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02