开发者

More concise assignment for elements in a list (Python)?

How can I do the following in a more concise, "pythonic" way:

for element in some_list:
       开发者_运维知识库 if some_condition:
                element.some_attr = some_value


The only thing that's not pythonic in your code is that you're not using 4 spaces for indentation.

“Pythonic” doesn't always mean “concise”; for example the following is shorter, but less readable than your loop:

[setattr(e, 'some_attr', some_value) for e in some_list if some_condition]

So, stick to the code you have.


any(setattr(element, "some_attr", some_value) for element in some_list if some_condition)

Not necessarily "more Pythonic" - but more concise. The function call do "any" is just to cause the generator to be consumed - as it is created as a lazy object, and the operations would only be performed when it's elements are fetched.


Your code is ok.

May be you can prefer this:

for element in some_list:
    element.some_attr = some_value if some_condition else element.some_attr

But it does useless assignements...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜