You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中按换行格式打印指定结构的列表?

问题说明

我需要把结构如下的列表:

[['Year', 'Salary', 'Yearly Income'], 
 [2, 2500, 30000], 
 [2, 3000.0, 36000.0], 
 [2, 3600.0, 43200.0], 
 [2, 4320.0, 51840.0], 
 [2, 5184.0, 62208.0], 
 [2, 6220.8, 74649.6]
]

按照上面这种每个子列表单独换行、带缩进的格式打印,用Python怎么实现?以下是我目前的代码:

work_experience = 0
year = 1
cnt =0
basic_salary = 2500
salary_list = [["Year", "Salary", "Yearly Income"]]

input_name = input("Please Enter Your Name: ")

print("Welcome ", input_name)

work_experience = int(input("How many years of work experience do you have? : "))

for years in range (int(work_experience / 2)):
    # calculate incremented salary after 2 years
    # Increment happens every 2 years with 20% and decimal precison of 2
    basic_salary = round(basic_salary + (basic_salary * 0.2), 2)

for years in range (6):
    # calculate yearly_income by multiplying current_salary with 12
    yearly_income = round((basic_salary * 12), 2)
    salary_list.append([year+1, basic_salary, yearly_income])
    # update current salary
    basic_salary = round(basic_salary + (basic_salary * 0.2), 2)

print(salary_list)

解决办法

方法1:手动控制格式输出

替换你代码里最后一行print(salary_list),改成下面的代码,就能精确控制每个子列表的换行和缩进:

print("[")
for idx, sub_list in enumerate(salary_list):
    # 把每个元素转成合适的字符串,字符串保留引号,数字直接转字符串
    elem_strs = []
    for elem in sub_list:
        if isinstance(elem, str):
            elem_strs.append(f'"{elem}"')
        else:
            elem_strs.append(str(elem))
    sub_list_str = ", ".join(elem_strs)
    # 最后一个子列表后面不加逗号
    end_char = "," if idx != len(salary_list)-1 else ""
    print(f"    [{sub_list_str}]{end_char}")
print("]")

方法2:用pprint模块快速实现

Python自带的pprint模块专门用来格式化打印复杂数据结构,一行代码就能搞定:

import pprint

# 替换原print语句
pprint.pprint(salary_list, indent=4)

indent=4指定缩进为4个空格,输出格式和你要的几乎一致,省心省力。

额外修复:Year列的问题

你代码里的year变量没更新,导致所有子列表的Year值都是2,在循环里加一行更新year就行:

for years in range (6):
    yearly_income = round((basic_salary * 12), 2)
    salary_list.append([year+1, basic_salary, yearly_income])
    basic_salary = round(basic_salary + (basic_salary * 0.2), 2)
    year += 1  # 新增这行,让Year值递增

内容的提问来源于stack exchange,提问作者ysncck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:50:39