2012-11-04 71 views
32

是否有一種簡單的內置方法可以將2D Python列表打印爲2D矩陣?漂亮打印2D Python列表

所以這個:

[["A", "B"], ["C", "D"]] 

會成爲像

A B 
C D 

我發現pprint模塊,但它似乎並沒有做我想做的。

+2

我會叫那個3D列表。如果你願意把它拉進來,'numpy'對於這種事情是非常好的。 – tacaswell

+0

@tcaswell:哎呀,對。我只是希望它被視爲一個2D矩陣。改變了這個問題,使這個明確的 – houbysoft

回答

47

爲了讓事情變得有趣,讓我們嘗試用一個更大的矩陣:

matrix = [ 
    ["Ah!", "We do have some Camembert", "sir"], 
    ["It's a bit", "runny", "sir"], 
    ["Well,", "as a matter of fact it's", "very runny, sir"], 
    ["I think it's runnier", "than you", "like it, sir"] 
] 

s = [[str(e) for e in row] for row in matrix] 
lens = [max(map(len, col)) for col in zip(*s)] 
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens) 
table = [fmt.format(*row) for row in s] 
print '\n'.join(table) 

輸出:

Ah!      We do have some Camembert sir    
It's a bit    runny      sir    
Well,     as a matter of fact it's very runny, sir 
I think it's runnier than you     like it, sir 

UPD:爲多細胞,這樣的事情應該工作:

text = [ 
    ["Ah!", "We do have\nsome Camembert", "sir"], 
    ["It's a bit", "runny", "sir"], 
    ["Well,", "as a matter\nof fact it's", "very runny,\nsir"], 
    ["I think it's\nrunnier", "than you", "like it,\nsir"] 
] 

from itertools import chain, izip_longest 

matrix = chain.from_iterable(
    izip_longest(
     *(x.splitlines() for x in y), 
     fillvalue='') 
    for y in text) 

然後應用上面的代碼。

又見http://pypi.python.org/pypi/texttable

+0

天才!但是如果我們想要在每個單元格內有多行,即3D陣列,該怎麼辦?) – CpILL

+0

@CpILL:一個選項是將3D解壓縮到2D中:[[[[a,b,c],[xyz]]] => [ [a,x],[b,y],[c,z]]'然後應用上述。 – georg

+0

你的意思是轉發數據? – CpILL

11

如果你可以用熊貓(Python數據分析庫),你幾乎可以打印一個二維矩陣將其轉換爲數據框對象:

from pandas import * 
x = [["A", "B"], ["C", "D"]] 
print DataFrame(x) 

    0 1 
0 A B 
1 C D 
+6

雖然這個答案可能是正確和有用的,但如果你[包括一些解釋一起](http://meta.stackexchange.com/q/114762/159034)來解釋它如何幫助解決問題,它是首選。如果存在導致其停止工作並且用戶需要了解其曾經工作的變化(可能不相關),這在未來變得特別有用。 –

+0

這正是我想要的。謝謝。 – Arvind

0

更輕量級的方法比pandas是使用prettytable模塊

from prettytable import PrettyTable 

x = [["A", "B"], ["C", "D"]] 

p = PrettyTable() 
for row in x: 
    p.add_row(row) 

print p.get_string(header=False, border=False) 

收率:

A B 
C D 

prettytable有許多選項以不同的方式設置輸出格式。

更多信息

-2

請看下面的代碼。

# Define an empty list (intended to be used as a matrix) 
matrix = [] 
matrix.append([1, 2, 3, 4]) 
matrix.append([4, 6, 7, 8]) 
print matrix 
# Now just print out the two rows separately 
print matrix[0] 
print matrix[1] 
+0

試試看看會發生什麼聽起來不像是答案。請查看:https:// stackoverflow。COM /幫助/如何到結果 – Daniel