Assign within if statement Python
问题 Is there a simpler alternative than res = returns_value_or_none(arg) if res: do_something_with(res) or if returns_value_or_none(arg): do_something_with(returns_value_or_none(arg)) One which combines the assignment and if conditional into one statement? 回答1: Often, what you have is already the best option. You can always create a new scope to bind the value to a variable: (lambda res: do_something_with(res) if res else None)(returns_value_or_none(arg)) But that's certainly not going to be more