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

Python循环中如何保存每次迭代的salary、cost_car变量值用于后续计算

实现方案

你只需要提前定义一个空列表,每次循环时将当前人员的两个字段数据存入列表即可,两种常用存储方式如下:

方法1:存为字典(可读性最高,后续取值更方便)

nr = int(input("How many people: "))
# 定义空列表存储所有人员信息
person_data = []

for i in range(1, nr+1, 1):
    print("For person ",i)
    salary = float(input("Salary per month : "))
    cost_car = float(input("Cost per month for car: "))
    # 把当前人员数据组装成字典存入列表
    person_data.append({
        "salary": salary,
        "cost_car": cost_car
    })

# 后续使用示例:
# 计算所有人的薪资总和
total_salary = sum([item["salary"] for item in person_data])
# 取第1位人员的用车成本(索引从0开始计数)
first_car_cost = person_data[0]["cost_car"]

方法2:存为元组(代码更简洁,适合不需要明确字段名的场景)

nr = int(input("How many people: "))
person_data = []

for i in range(1, nr+1, 1):
    print("For person ",i)
    salary = float(input("Salary per month : "))
    cost_car = float(input("Cost per month for car: "))
    # 按(薪资, 用车成本)的固定顺序存入元组
    person_data.append((salary, cost_car))

# 后续使用示例:取第2位人员的薪资
second_salary = person_data[1][0]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 04:45:06