使用Lambda函数更改属性的值 [英] Using lambda function to change value of an attribute

查看:724
本文介绍了使用Lambda函数更改属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用lambda函数遍历一类类对象并更改属性值(对于所有对象还是满足特定条件的对象)?

Can I use lambda function to loop over a list of class objects and change value of an attribute (for all objects or for the one that meet a certain condition)?

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]

new_list_of_students = map(lambda student:student.age+=3,students)

推荐答案

不幸的是,由于 lambda正文仅允许简单的表达式 ,而student.age += 3 声明 .因此,您不能在其中使用Lambda.但是,您仍然可以使用地图解决方案:

Unfortunately, that’s not possible since the body of a lambda only allows for simple expressions while a student.age += 3 is a statement. So you can’t use a lambda there. You could however still use the map solution:

def incrementAge (student):
    student.age += 3
    return student

students2 = map(incrementAge, students)

请注意,尽管students2将包含与students相同的学生,所以您实际上并不需要捕获输出(或从incrementAge返回值).还要注意,在Python 3中,map返回一个生成器,您首先需要对其进行迭代.您可以在其上调用list()来执行此操作:list(map(…)).

Note that students2 will contain the same students as students though, so you don’t really need to capture the output (or return something from incrementAge). Also note that in Python 3, map returns a generator which you need to iterate on first. You can call list() on it to do that: list(map(…)).

最后,一个更好的解决方案是使用一个简单的循环.这样,您就不需要任何功能或创建重复的学生列表,也可以使意图非常清楚:

Finally, a better solution for this would be to use a simple loop. That way, you don’t have overhead of needing a function or create a duplicate students list, and you would also make the intention very clear:

for student in students:
    student.age += 3

这篇关于使用Lambda函数更改属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆