python - python循环中的变量
问题描述
如何在每次运行后(例如可以是 3 人)保存每个变量(salary 和 cost_car)的数据,以便以后使用它进行计算。
nr = int(input("How many people: "))
total = 0
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: "))
解决方案
您可以使用多种数据结构将数据存储在正在运行的程序中。由于您的人员在您的示例中被编号,因此将每个人的信息存储在列表中是有意义的。您可以将每个人的信息表示为一个简单的字典,其中的键代表不同信息的名称:
nr = int(input("How many people: "))
total = 0
persons_info = []
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: "))
info = {salary: salary, cost_car: cost_car} # the info of person i
persons_info.append(info) # store it in the list of all persons info
然后,您可以在 for 循环之后通过执行以下操作检索人员 n 的信息:(persons_info[n-1]
因为列表索引从 0 开始),这将为您提供他们信息的字典。
更好的方法是用一个对象来表示每个人,即表示与真实人相关的信息Person
的某个类的实例。Person
这样,您还可以包含并实现您希望在Person
类中执行的不同操作:
class Person:
def __init__(self, salary, cost_car):
self.salary = salary
self.cost_car = cost_car
def getNetWorth(self):
return self.salary + self.cost_car
nr = int(input("How many people: "))
total = 0
persons = []
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 = Person(salary, cost_car) # an object representing person i
persons.append(info) # store it in the list of all person objects
再次,您可以通过执行以下操作检索人员 n 的信息:(persons_info[n-1]
因为列表索引从 0 开始),这将为您提供一个表示其信息的对象。
推荐阅读
- python - Discord.py bot 不会加入 vc
- replication - 如何计算复制因子 3 与 5 与 9 之间的可用性差异
- amazon-web-services - 无法将 kubectl apply -f 应用于我的 EKS 集群:访问被拒绝(root 帐户可能不承担角色)
- mysql - 对大量记录有更好的查询性能
- python - 登录未重定向到 django 上的指定 url
- python - 提高嵌套 for 循环计数到字典中的效率 - Python
- c# - WinUI ItemsRepeater如何添加交错的项目入口动画?
- html - 选择 DIV 与另一个 DIV 之外的 DIV 父级使用严格的 CSS
- python - 安装 VS Code 包以在多个 Conda 环境中工作
- wordpress - 显示锚内容的 Wordpress 插件