2016-04-23 55 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

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

相关问题