Python不调包实现条形图 Python手写条形图
Python3版
def bars(values, labels=None):
labels = labels or [str(i + 1) for i in range(len(values))]
maximum = max(values)
label_max_length = max(len(label) for label in labels)
for value, label in zip(values, labels):
length = int(value / maximum * 100)
print('%{}s'.format(label_max_length) % label, '#' * length, value)
bars([9, 15, 22, 50])
bars([9, 45, 22, 5], ['a', 'bb', 'ccc', 'MapReduce'])
效果
兼容Python2和3的版本
def bars(values, labels=None, scaling=100):
"""
values: 数据列表
labels: 标签列表
scaling: 缩放比例
"""
labels = labels or [str(i + 1) for i in range(len(values))]
maximum = max(values)
label_max_length = max(len(label) for label in labels)
for value, label in zip(values, labels):
length = int((scaling * value) / maximum)
print('{} {} {}'.format('%{}s'.format(label_max_length) % label, '#' * length, value))
bars([9, 15, 22, 50])
bars([9, 45, 22, 5], ['a', 'bb', 'ccc', 'MapReduce'])
|