简体   繁体   English

格式化与其他变量串联的列表的打印

[英]Formatting the printing of list concatenated with other variables

I have a list data and its mean , median and mode as below: 我有一个列表数据及其平均值中位数众数 ,如下所示:

data = [2, 3, 5, 5, 7, -6, -6, 9]
mean = 2.00
median = 3.00
mode = [5, -6]

I want to have a neat Pythonic output of the results. 我想要结果的整洁的Pythonic输出。 Using the answers recommended here and here I have come up with the following code. 使用此处此处建议的答案,我得出了以下代码。

print('Mean:{0:9.2f}\nMedian:{1:7.2f}'.format(mean, median),
  ''.join('\nMode: {}: {}'.format(*k) for k in enumerate(mode)))

However, I'm not confident if this is a good solution anyway and my output looks like this: 但是,我不确定这是否是一个好的解决方案,我的输出看起来像这样:

Mean:     2.38
Median:   4.00 
Mode: 0: -6
Mode: 1: 5

I want an output like: 我想要这样的输出:

Mean:     2.38
Median:   4.00
Mode:     -6, 5

I would just use tabs: 我只会使用标签:

print('Mean:\t{}\nMedian:\t{}\nMode:\t{}'.format(mean,median,', '.join(str(i) for i in mode)))

giving: 赠送:

Mean:   2.0
Median: 3.0
Mode:   5, -6

Use str.ljust() to make sure your titles (eg Mean , Median ) have a fixed length: 使用str.ljust()确保标题(例如MeanMedian )具有固定的长度:

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]))

Output: 输出:

Mean:     2.00
Median:   3.00
Mode:     5: -6

format() can still be used as follows: 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))))

Giving you: 给你:

Mean:   2.00
Median: 3.00
Mode:   5, -6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM