如何对齐Python二维列表输出,让股票投资组合打印排版整齐?
问题解决方案
方法1:手动指定列宽格式化(无需额外依赖)
通过Python字符串格式化语法为每一列固定显示宽度,文本类字段左对齐、数值类字段右对齐,即可保证排版整齐,适配学校项目这类需求固定的场景:
listofstock=[] listofstock.append(["No","Company","Cap","Qty","BoughtPrice","MarketPrice"]) listofstock.append([1,"Microsoft","Mega",100,188,207]) listofstock.append([2,"Amazon","Mega",5,1700,3003]) listofstock.append([3,"PayPal","Large",80,100,188]) listofstock.append([4,"Apple","Large",100,60,110]) listofstock.append([5,"Fastly","Mid",30,40,76]) listofstock.append([6,"Square","Mid",30,40,178]) # 按列顺序定义每列的显示宽度 col_widths = [3, 12, 6, 5, 12, 13] for row in listofstock: # 前3列为文本类,左对齐;后3列为数值类,右对齐更易读 print(f"{row[0]:<{col_widths[0]}}" f"{row[1]:<{col_widths[1]}}" f"{row[2]:<{col_widths[2]}}" f"{row[3]:>{col_widths[3]}}" f"{row[4]:>{col_widths[4]}}" f"{row[5]:>{col_widths[5]}}")
输出效果如下:
No Company Cap Qty BoughtPrice MarketPrice 1 Microsoft Mega 100 188 207 2 Amazon Mega 5 1700 3003 3 PayPal Large 80 100 188 4 Apple Large 100 60 110 5 Fastly Mid 30 40 76 6 Square Mid 30 40 178
方法2:自动计算列宽(适配动态数据)
如果后续可能新增不同长度的公司名称等动态数据,可以先遍历所有内容计算每列的最大宽度,再做格式化,无需手动调整宽度值:
listofstock=[] listofstock.append(["No","Company","Cap","Qty","BoughtPrice","MarketPrice"]) listofstock.append([1,"Microsoft","Mega",100,188,207]) listofstock.append([2,"Amazon","Mega",5,1700,3003]) listofstock.append([3,"PayPal","Large",80,100,188]) listofstock.append([4,"Apple","Large",100,60,110]) listofstock.append([5,"Fastly","Mid",30,40,76]) listofstock.append([6,"Square","Mid",30,40,178]) # 自动计算每列的最大宽度 col_widths = [0]*len(listofstock[0]) for row in listofstock: for idx, col in enumerate(row): col_widths[idx] = max(col_widths[idx], len(str(col))) for row in listofstock: for idx, col in enumerate(row): if isinstance(col, str): print(f"{col:<{col_widths[idx]}} ", end="") else: print(f"{col:>{col_widths[idx]}} ", end="") print()
方法3:使用第三方库快速实现(适合开发效率优先场景)
如果允许引入第三方依赖,tabulate库可以直接把二维列表转换为对齐的文本表格,无需自己写格式化逻辑:
- 安装依赖:
pip install tabulate - 代码实现:
from tabulate import tabulate listofstock=[] listofstock.append(["No","Company","Cap","Qty","BoughtPrice","MarketPrice"]) listofstock.append([1,"Microsoft","Mega",100,188,207]) listofstock.append([2,"Amazon","Mega",5,1700,3003]) listofstock.append([3,"PayPal","Large",80,100,188]) listofstock.append([4,"Apple","Large",100,60,110]) listofstock.append([5,"Fastly","Mid",30,40,76]) listofstock.append([6,"Square","Mid",30,40,178]) print(tabulate(listofstock[1:], headers=listofstock[0], tablefmt="simple"))
内容的提问来源于stack exchange,提问作者RpNeverKeel
相关产品推荐
相关产品推荐

