我有一个列表数据及其意思,中位数和模式,如下所示:
data = [2, 3, 5, 5, 7, -6, -6, 9]
mean = 2.00
median = 3.00
mode = [5, -6]
我希望得到结果的整齐Pythonic输出。使用建议的答案here和here,我提出了以下代码。
print('Mean:{0:9.2f}\nMedian:{1:7.2f}'.format(mean, median),
''.join('\nMode: {}: {}'.format(*k) for k in enumerate(mode)))
但是,我不相信这是否是一个好的解决方案,我的输出看起来像这样:
Mean: 2.38
Median: 4.00
Mode: 0: -6
Mode: 1: 5
我想输出如下:
Mean: 2.38
Median: 4.00
Mode: -6, 5
答案 0 :(得分:2)
我只想使用标签:
FUNCTION(data = df_data, X = id, Y = 1)
# A tibble: 1 x 3
# year id value
# <dbl> <dbl> <dbl>
#1 2004 1 10
,并提供:
print('Mean:\t{}\nMedian:\t{}\nMode:\t{}'.format(mean,median,', '.join(str(i) for i in mode)))
答案 1 :(得分:1)
使用str.ljust()
确保您的标题(例如Mean
,Median
)具有固定长度:
TITLE_LENGTH = 10
print("Mean:".ljust(TITLE_LENGTH) + "{:.2f}".format(mean))
print("Median:".ljust(TITLE_LENGTH) + "{:.2f}".format(median))
print("Mode:".ljust(TITLE_LENGTH) + "{}: {}".format(mode[0], mode[1]))
输出:
Mean: 2.00
Median: 3.00
Mode: 5: -6
答案 2 :(得分:1)
format()
仍可按如下方式使用:
data = [2, 3, 5, 5, 7, -6, -6, 9]
mean = 2.00
median = 3.00
mode = [5, -6]
print('Mean: {:.2f}\nMedian: {:.2f}\nMode: {}'.format(mean, median, ', '.join(map(str, mode))))
给你:
Mean: 2.00
Median: 3.00
Mode: 5, -6