Updating object properties in list comprehension way

老子叫甜甜 提交于 2020-05-12 11:25:36

问题


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:

result = [ object.name = "blah" for object in objects]

or with map function

result = map(object.name = "blah", objects)

Could it be achieved without for-looping with property setting?

(Note: all above examples are intentionally wrong and provided only to express the idea)


回答1:


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.



来源:https://stackoverflow.com/questions/16650369/updating-object-properties-in-list-comprehension-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!