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. 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:
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.