Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我的问题是基本的,可能是重复的,但我还没有找到答案。
我正在寻找将 1 添加到x给定列表的所有对象的属性的最有效(pythonic)方法。
x
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)]
有没有比(例如使用列表理解)更好的解决方案:
for i in l: i.x += 1
您的代码没有问题,但是如果您想在理解中使用它,请添加“增量”方法:
def inc(self, amount=1): self.x += amount return self
你的方式完全是pythonic。