如何在Python中不使用matplotlib生成星号组成的垂直直方图
垂直直方图功能实现方案
实现思路
- 新增全局统计变量,累计记录每类学业进展结果的录入数量
- 单学生结果判定完成后,对应分类计数+1
- 用户输入
q触发退出时,按以下逻辑生成纯字符垂直直方图:- 取四类计数的最大值作为直方图的总高度,适配任意数量的统计结果
- 从上到下逐行渲染:每一行遍历四类计数,若当前分类计数大于已渲染行数则输出
*,否则输出等宽占位空格,保证列对齐 - 最后渲染分类名称标签,与上方直方图列一一对应
完整实现代码
def get_progress_result(pass_credit, defer_credit, fail_credit): # 可根据实际判定规则调整此处逻辑 if pass_credit == 120: return "progress" elif fail_credit <= 30 and pass_credit >= 90: return "trailing" elif fail_credit <= 60: return "module retriever" else: return "exclude" def draw_vertical_histogram(counts): categories = ["Progress", "Trailing", "Module Retriever", "Exclude"] max_height = max(counts.values()) col_width = 18 # 保证列对齐,可根据名称长度调整 # 渲染星号行,从上到下 for i in range(max_height): line = "" for cat in categories: if counts[cat.lower()] > i: line += "*".ljust(col_width) else: line += " ".ljust(col_width) print(line) # 渲染分类标签行 label_line = "" for cat in categories: label_line += cat.ljust(col_width) print(label_line) # 输出统计数值 count_line = "" for cat in categories: count_line += str(counts[cat.lower()]).ljust(col_width) print(count_line) if __name__ == "__main__": # 初始化统计计数器 result_counts = { "progress": 0, "trailing": 0, "module retriever": 0, "exclude": 0 } while True: # 录入学分 try: pass_credit = int(input("请输入通过学分:")) defer_credit = int(input("请输入缓考学分:")) fail_credit = int(input("请输入不及格学分:")) except ValueError: print("输入无效,请输入数字") continue # 校验总学分是否为120,可根据实际规则调整 if pass_credit + defer_credit + fail_credit != 120: print("总学分需为120,请重新输入") continue # 判定结果并更新统计 res = get_progress_result(pass_credit, defer_credit, fail_credit) print(f"该生学业进展结果:{res}") result_counts[res] += 1 # 询问是否继续 op = input("输入y继续,输入q退出:").strip().lower() if op == 'q': print("\n=== 学业进展结果统计垂直直方图 ===") draw_vertical_histogram(result_counts) break elif op != 'y': print("无效输入,默认继续")
效果示例
如果累计统计结果为progress 3例、trailing 2例、module retriever 1例、exclude 4例,输出的直方图格式如下:
* * * * * * * * * * Progress Trailing Module Retriever Exclude 3 2 1 4
内容的提问来源于stack exchange,提问作者KaranK
相关产品推荐
相关产品推荐

