您可以浏览数据并获取最大字段宽度,然后使用它们来对齐所有内容:
data = [
['tabby, tabby cat', 281, 0.312437],
['tiger cat', 282, 0.237971],
['Egyption cat', 285, 0.123873],
['red fox, Vulpes vulpes', 277, 0.100757],
['lynx, catamount', 287, 0.709574]
]
max_class_width = len('Predicted Classes')
max_index_width = len('Class Index')
max_proba_width = len('Probability')
for entry in data:
max_class_width = max(max_class_width, len(entry[0]))
max_index_width = max(max_index_width, len(str(entry[1])))
max_proba_width = max(max_proba_width, len(str(entry[2])))
print "{1:<{0}s} {3:<{2}s} {5:<{4}}".format(max_class_width, 'Predicted Classes',
max_index_width, 'Class Index',
max_proba_width, 'Probability')
for entry in data:
print "{1:<{0}s} {3:<{2}s} {5:<{4}}".format(max_class_width, entry[0],
max_index_width, str(entry[1]),
max_proba_width, str(entry[2]))
输出
Predicted Classes Class Index Probability
tabby, tabby cat 281 0.312437
tiger cat 282 0.237971
Egyption cat 285 0.123873
red fox, Vulpes vulpes 277 0.100757
lynx, catamount 287 0.709574
您还可以使用printf
样式格式:
print "%-*s %-*s %-*s" % (max_class_width, 'Predicted Classes',
max_index_width, 'Class Index',
max_proba_width, 'Probability')
for entry in data:
print "%-*s %-*s %-*s" % (max_class_width, entry[0],
max_index_width, str(entry[1]),
max_proba_width, str(entry[2]))