简体   繁体   English

将用户输入的信息保存在列表中以备后用

[英]Save information input of user in list to use it later

name=input("name: ")
age=input("age: ")
sallary=input("sallary: ")


employee_info={
 name:(age,salary )
}
employee_info[name].append(age,salary)

I need when a user input iformation of a employee the program save it in list, i make this code but the error was (attributeError:'tuple' object has no attribute 'append')我需要当用户输入员工信息时,程序将其保存在列表中,我制作此代码但错误是(attributeError:'tuple' object has no attribute 'append')

any solve or suggestions任何解决方案或建议

the problem is that you are using a tuple instead of a list and you can't append a variable to a tuple问题是您使用的是元组而不是列表,并且您不能 append 将变量转换为元组

this should do the trick:这应该可以解决问题:

name=input("name: ")
age=input("age: ")
salary=input("salary: ")


employee_info={
 name:[age,salary ]#the row i changed
}
employee_info[name].append((age,salary))

But why do you want to add the age and salary to the employee_info[name] (since they are already there)但是为什么要将年龄和薪水添加到employee_info[name] (因为它们已经存在)

As you learned from the comments, you need to use a list instead of a tuple.正如您从评论中了解到的,您需要使用列表而不是元组。 This is because tuples are immutable - you cannot change them once created.这是因为元组是不可变的——一旦创建就不能更改它们。 That is, you cannot change their element values or remove or add elements.也就是说,您不能更改它们的元素值或删除或添加元素。

On the other hand, after the fixes, you're actually appending age and salary to an existing list [age, salary].另一方面,在修复之后,您实际上是将年龄和薪水附加到现有列表 [年龄,薪水] 中。 If not intended, I suggest you use this snippet instead:如果不是故意的,我建议您改用此代码段:

# Dictionary with employee data
employee_info = {}

# Input for one employee
name = input("name: ")
age = input("age: ")
sallary = input("sallary: ")

# Store it
employee_info[name] = [age, sallary]

# Then reuse it
print(employee_info)

Here you would initialize the dictionary up front.在这里,您将预先初始化字典。 Then the user can create an employee that you would add to your dictionary.然后,用户可以创建您将添加到字典中的员工。 At that spot you can also prompt the user to input data on many employees using (commonly) a while loop.在那个地方,您还可以提示用户使用(通常)while 循环输入许多员工的数据。 In the loop, you would be adding all new employees to the dictionary.在循环中,您会将所有新员工添加到字典中。 Finally - once collected, you could reuse the data later in the code.最后 - 一旦收集,您可以稍后在代码中重用数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM