does python have a comma operator like C
in C (and C family o开发者_如何学运维f languages) an expression (4+7, 5+2)
returns 7
. But the same expression in Python would result in a tuple (11, 7)
So does python have a comma operator like C ?
You should use something like this to replace it:
comma_operated = (4+7, 5+2)[-1]
but as noted correctly in the comments, why would you want it? It is used in C or C++ quite seldomly and there are good reasons for that.
AFAIK, no. Though you can always simulate this by using two lines instead of one. :-)
x = (call_one(), call_two())
# is almost the same as
call_one()
x = call_two()
# or
x = (call_one(), call_two())[1]
An update to this question.
As it stands the accepted answer is incomplete since it does not allow assignment expressions to be used in this manner, (e.g. (a = 1, a+2)[-1]
would generate an error).
Python 3.8 is now coming up with Assignment Expressions which in theory should make this possible, i.e.
( a := 1, a + 2)[-1]
精彩评论