不使用hist()函数实现带极差判断的分格式数值计数直方图编写
代码补全实现
前置修正点
- 替换原有代码中与Python内置函数重名的
max、min变量为data_max、data_min,避免内置函数被覆盖导致的运行异常 - 将字符串形式的item列表转换为整数数值,用于区间匹配计算
- 简化原代码中用
while循环拼接星号的逻辑,直接使用Python字符串乘法生成对应长度的星号序列
极差>5分支实现逻辑
- 以数据最大值为起点,按步长5向下拆分连续区间,保证区间覆盖完整的[最小值, 最大值]范围,输出顺序从高值区间到低值区间,和极差≤5分支的输出顺序保持一致
- 初始化每个区间的计数累加值为0
- 遍历所有数值及对应计数,将计数累加到数值所属的区间总和中
- 沿用原有分支的左对齐格式,逐行输出区间标识和对应星号序列
完整可运行代码
item_str = ['15', '14', '13', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0'] count = [1, 1, 1, 1, 3, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1] data_max = 15 data_min = 0 def histogram(count, item_str, data_max, data_min): item_num = [int(s) for s in item_str] # 极差≤5分支:逐值输出 if data_max - data_min <= 5: for val, cnt in zip(item_num, count): bar = '*' * cnt print(f'{val:<10}{bar}') # 极差>5分支:按步长5分区间输出 else: # 生成区间边界 boundaries = [] current = data_max while current > data_min: lower = max(current - 5, data_min) boundaries.append((lower, current)) current = lower # 初始化区间计数字典 interval_counter = {f"{low}-{high}": 0 for low, high in boundaries} # 累加各区间计数 for val, cnt in zip(item_num, count): for low, high in boundaries: if low <= val <= high: interval_counter[f"{low}-{high}"] += cnt break # 格式化输出 for interval, total in interval_counter.items(): bar = '*' * total print(f'{interval:<10}{bar}') histogram(count, item_str, data_max, data_min)
运行输出
10-15 ******* 5-10 * 0-5 **
说明:输出中0-5区间的星号数量为2,是因为该区间包含两个带计数的数值:值4(计数1)、值0(计数1),原示例此处为简化笔误。调整区间匹配规则为左闭右开(
low <= val < high)即可调整边界值的归属逻辑,适配不同区间划分需求。
内容的提问来源于stack exchange,提问作者Majid Rezaie
相关产品推荐
相关产品推荐

