2016-04-23 57 views
0
for k, v in sorted(total_prob.items(), key = lambda x: x[1], reverse=True): 
    MLE_Prob, Bi_Prob = v 
    # here, k = tuple type of bigrams. v = tuple type of (mle prob, bi prob) 
    print tabulate([k,v[0], v[1]], headers = ["Bigram", "MLE_Prob", "Bi_Prob"], tablefmt="grid") 

我的數據包括像{(a,b):(c,d)}。我想打印的結果是如何以表格格式打印關鍵字爲元組並且值爲元組的字典?

header1  header2 header3 
(a, b)   c   d 

但我得到了類型錯誤,'float'對象是不可迭代的。 mle prob和bi prob都是浮動的,它的值通常是0.0022323xxx。 如何解決這個錯誤?

回答

0

首先,您需要創建包含結果的數組,然後使用製表符顯示它。您不能逐行顯示,而是一次顯示整個網格。

from tabulate import tabulate 

total_prob = {("a", "b"): (1, 2), ("c", "d"): (3, 4)} 
results = [] 
for k, v in sorted(total_prob.items(), key = lambda x: x[1], reverse=True): 
    MLE_Prob, Bi_Prob = v 
    results.append([k,MLE_Prob, Bi_Prob]) 

print tabulate(results, headers = ["Bigram", "MLE_Prob", "Bi_Prob"], tablefmt="grid") 

輸出:

+------------+------------+-----------+ 
| Bigram  | MLE_Prob | Bi_Prob | 
+============+============+===========+ 
| ('c', 'd') |   3 |   4 | 
+------------+------------+-----------+ 
| ('a', 'b') |   1 |   2 | 
+------------+------------+-----------+ 

製表需要數組的數組(行陣列)作爲第一個參數。所以至少你需要使用這樣的表格:tabulate([[k,v[0], v[1]]],...,但輸出將是這樣的:

+------------+------------+-----------+ 
| Bigram  | MLE_Prob | Bi_Prob | 
+============+============+===========+ 
| ('c', 'd') |   3 |   4 | 
+------------+------------+-----------+ 
+------------+------------+-----------+ 
| Bigram  | MLE_Prob | Bi_Prob | 
+============+============+===========+ 
| ('a', 'b') |   1 |   2 | 
+------------+------------+-----------+ 
+0

非常感謝我真的很感激它。 –