[英]Python: Modifying one attribute to each object in a list
My question is basic and is maybe a duplicate but I haven't found the answer. 我的问题是基本的,可能是重复的,但我没有找到答案。
I am looking for the most efficient (pythonic) way of adding 1 to the attribute x
of all objects of a given list. 我正在寻找将1添加到给定列表的所有对象的属性
x
的最有效(pythonic)方法。
class Any(object):
def __init__(self, x):
self.x = x
l = [Any(1), Any(-3), Any(1), Any(4), Any(6), Any(7), Any(3)]
Is there a better solution than (using list comprehension for example): 有没有比(例如,使用列表理解)更好的解决方案:
for i in l:
i.x += 1
Nothing wrong with your code, but if you want to use it in a comprehension, add an "increment" method: 您的代码没什么问题,但是,如果您想在理解中使用它,请添加一个“增量”方法:
def inc(self, amount=1):
self.x += amount
return self
您的方式完全是pythonic。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.