Python仅同时从列表的某些元素分配 [英] Python simultaneous assign only from some elements of a list
问题描述
在Python中,我可以这样做
In Python I can do this
w,x,y,z = (1,1,2,3)
但是假设我只需要x和y的值.有没有办法只同时分配几个变量(同时仍然保持优美的同时分配语法?).我希望能找到一些与MATLAB的波浪符号运算符相似的东西
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.
推荐答案
在Python中,做您正在做的事情的适当方法是实际使用'_'作为您的丢弃"变量.因此,您在做什么方面非常接近.只需执行以下操作:
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:
这篇关于Python仅同时从列表的某些元素分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!