以列表理解方式更新对象属性 [英] Updating object properties in list comprehension way

查看:54
本文介绍了以列表理解方式更新对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是否有可能以列表理解或类似的方式更新对象列表? 例如,我想设置列表中所有对象的属性:

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]

或带有map功能

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)

推荐答案

最终,赋值是声明",而不是表达式",因此不能在lambda表达式或列表理解中使用.您需要一个常规函数来完成您要尝试的工作.

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.

有一个内置函数可以执行此操作(返回None的列表):

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.

如果您确实需要1-liner(尽管我不知道为什么):

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

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


我发现大多数人都想使用列表理解,因为有人告诉他们快速".是正确的,但仅用于创建新列表.使用列表推导来产生副作用不太可能带来任何性能上的好处,并且代码的可读性会受到影响.确实,使用列表推导而不是.append的等效循环的最重要原因是因为它更易于阅读.


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.

这篇关于以列表理解方式更新对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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