你尝试过使用
setattr 和
getattr 函数吗?使用它们,你可以直接读写对象的可写属性。
你可以像这样进行操作:
map_of_students = map(lambda student: setattr(student, "age", getattr(student, "age") + 3), students)
print("Age BEFORE list: " + str(students[0].age)); list(map_of_students); print("Age AFTER list: " + str(students[0].age))
在这种情况下,原始学生列表将被更新为每个学生的新年龄,这可能不是您想要的,但可以通过在将映射对象转换为列表之前备份原始列表对象来轻松解决。在这种情况下,您可以执行以下操作:
students_bkp = []
for s in students:
students_bkp.append(Student(**s.__dict__))
以下是完整的代码片段:
class Student(object):
def __init__(self,name,age):
self.name = name
self.age = age
student1 = Student('StudOne',18)
student2 = Student('StudTwo',20)
student3 = Student('StudThree',29)
students = [student1,student2,student3]
students_bkp = []
for s in students:
students_bkp.append(Student(**s.__dict__))
map_of_students = map(lambda student: setattr(student, "age", getattr(student, "age") + 3), students)
print("Age BEFORE list: " + str(students[0].age)); list(map_of_students); print("Age AFTER list: " + str(students[0].age)); print("Age BKP: " + str(students_bkp[0].age))
increased_students_age_list
和students
的内容完全相同。你有两个完全相同的列表,这没有任何意义。 - Ned Batchelder