Cleaner assignment in for loop (python)
I have a nodelist
object that yields a bunch of node
objects on iteration. I need to increment these nodes based on some random condition (like node.x > 17
). Here's what I'm doing right now:
for node in nodelist:
if node.x > 17:
node.x += 1
I can't do map(lambda node: node.x += 1, nodelist)
because lambda can't contain assignment. I cannot do nodelist = [node.x + 1 for node in nodelist if...]
because a nodelist
object consists of more than just its child nodes.
Is there a way to make th开发者_如何学JAVAis shorter/cleaner?
I think it's already pretty short and clean. Python provides some powerful tools, but sometimes simple is best; this seems like one of those times.
I also think what you have is more readable than any equivalent one-liner (that I can come up with).
Ok, that said, you could do this:
for node in (n for n in nodelist if condition):
node.x += 1
That could even be compressed into one line. But I honestly prefer the way you have it now.
You can actually assign in a lambda:
import operator
map(lambda node: operator.iadd(node.x,1), nodelist)
respectively
[operator.iadd(node.x,1) for node in nodelist if ...]
apart from that, your code is not really bad - it is quite concise and easy to read as is.
I vote that You are overdoing this pythonic thing :)
What is your goal: performance? I doubt You will get any.
Readability? Well, for three lines, I am not sure if functional collapse will help in this case, as it obviously will not be so obvious.
You can actually use lambda:
map(lambda node: node.x>17 and node.x+1 or node.x, nodelist)
精彩评论