问题
In Python I can do this
w,x,y,z = (1,1,2,3)
But suppose I only need the values of x and y. Is there a way to only simultaneously assign a few variables (while still keeping the beautiful simultaneous assignment syntax?). I'm hoping to find something along the lines of MATLAB's tilde operator
~,x,y,~ = (1,1,2,3) # This is not valid Python code
I'm aware that I can just define a dummy variable to do this,
d,x,y,d = (1,1,2,3)
But I am curious if there is a special operator just for this purpose.
回答1:
In Python, the appropriate way to do what you are doing is to actually make use of the '_' as your "throwaway" variable. So, you are very close in what you are doing. Simply do this:
_, x, y, _ = (1,1,2,3)
Here is some information on the single underscore character:
What is the purpose of the single underscore "_" variable in Python?
来源:https://stackoverflow.com/questions/33003633/python-simultaneous-assign-only-from-some-elements-of-a-list