Re: [問題] Print matrix formatting problem

看板Python作者 (←這人是超級笨蛋)時間12年前 (2011/09/29 23:49), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/3 (看更多)
一個方法是繼承 numpy.matrix 然後 override 它的 __str__ function 當你 print 一個非字串物件時, python 會呼叫這個 function 把物件轉成字串 舉個簡單的例子 >>> class MyList(list): ... def __str__(self): ... return '\t'.join([str(i) for i in self]) ... >>> a = [1, 2, 3] >>> print(a) [1, 2, 3] >>> print(MyList(a)) 1 2 3 >>> 要怎麼轉給 numpy.matrix, 以及怎麼寫成二維使用, 就留給你自己發揮了 當然一般輸出 csv 之類的格式都是寫到檔案, 直接另外寫兩層迴圈來輸出也很容易 不過這個方法的優點是, 配合 print 的重導向功能, 可以讓寫檔的程式碼變得很漂亮 ※ 引述《mark038 (Mark)》之銘言: : I can't type Chinese in the computer now. Sorry蔊: The following is my output if I print a matrix (I used numpy) from a : generated m*n matrix. : But I want to generate/print a tab delimited file for reading/opening excel. : Could anybody provide a clever solution? : Thanks! : [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. : 0. 0. 0. 0. 0. 0. 0. 0.] : [ 0. 1. 0. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. : 0. 0. 0. 0. 0. 0. 0. 1.] : [ 0. 0. 4. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. : 0. 0. 0. 0. 0. 0. 0. 0.] : [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. : 0. 0. 0. 0. 0. 0. 0. 0.] : [ 1. 0. 0. 0. 0. 0. 0. 1. 0. 1. 0. 0. 1. 0. 1. 0. 0. 1. : 0. 0. 1. 1. 0. 0. 0. 0.] : [ 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 3. 0. 0. 1. 0. 1. 0. 0. : 1. 0. 0. 0. 1. 0. 0. 0.] : [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. : 0. 1. 0. 0. 0. 0. 0. 0.] : [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. : 0. 0. 0. 0. 0. 1. 0. 0.] : [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. : 0. 0. 0. 0. 0. 0. 1. 0.] : [ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. : 0. 0. 0. 0. 0. 0. 0. 0.]] -- "問おう、貴方が私のマスターか?" -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.32.81.146

09/29 23:57, , 1F
09/29 23:57, 1F
※ 編輯: uranusjr 來自: 114.32.81.146 (09/30 00:19)

10/01 11:31, , 2F
Thanks!
10/01 11:31, 2F
文章代碼(AID): #1EX9DnEq (Python)
文章代碼(AID): #1EX9DnEq (Python)