Updating object properties in list comprehension way

前端 未结 1 1089
忘掉有多难
忘掉有多难 2021-02-19 10:04

Is that possible, in Python, to update a list of objects in list comprehension or some similar way? For example, I\'d like to set property of all objects in the list:



        
1条回答
  •  孤城傲影
    2021-02-19 10:54

    Ultimately, assignment is a "Statement", not an "Expression", so it can't be used in a lambda expression or list comprehension. You need a regular function to accomplish what you're trying.

    There is a builtin which will do it (returning a list of None):

    [setattr(obj,'name','blah') for obj in objects]
    

    But please don't use it. Just use a loop. I doubt that you'll notice any difference in efficiency and a loop is so much more clear.

    If you really need a 1-liner (although I don't see why):

    for obj in objects: obj.name = "blah"
    

    I find that most people want to use list-comprehensions because someone told them that they are "fast". That's correct, but only for creating a new list. Using a list comprehension for side-effects is unlikely to lead to any performance benefit and your code will suffer in terms of readability. Really, the most important reason to use a list comprehension instead of the equivalent loop with .append is because it is easier to read.

    0 讨论(0)
提交回复
热议问题