Python simultaneous assign only from some elements of a list

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 03:38:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!