Python如何用for循环打印不同范围的多列,实现垂直直方图?
问题原因
你使用zip()同时遍历4个range对象时,zip的特性是以最短的可迭代对象的长度作为总遍历次数,你定义的tot_progress = 2是四个值里最小的,所以循环只执行2次,最终只输出2行星号。
修正思路
- 先取四个统计值的最大值作为总循环行数,保证最高的列能完整输出
- 每一行遍历四个统计值,判断当前行号是否小于对应统计值:小于则输出
*,否则输出空白占位 - 固定列宽保证对齐,避免输出错位
修正后代码
tot_progress = 2 tot_trailer = 4 tot_retriever = 3 tot_exclude = 4 # 存四个值和对应列名,方便后续遍历 counts = [tot_progress, tot_trailer, tot_retriever, tot_exclude] headers = ["Progress", "Trailing", "Retriever", "Excluded"] # 打印表头,固定每列宽度为12字符保证对齐 for header in headers: print(f"{header:<12}", end="") print() # 取最大值作为总行数 max_row = max(counts) a = '*' for row in range(max_row): for cnt in counts: # 当前行数小于计数则输出*,否则输出空白,同样固定宽度 print(f"{a:<12}" if row < cnt else f"{'':<12}", end="") print()
运行效果
Progress Trailing Retriever Excluded * * * * * * * * * * * * *
内容的提问来源于stack exchange,提问作者GSujiKanth
相关产品推荐
相关产品推荐

