Ignore part of a python tuple

杀马特。学长 韩版系。学妹 提交于 2020-06-10 02:08:21

问题


If I have a tuple such as (1,2,3,4) and I want to assign 1 and 3 to variables a and b I could obviously say

myTuple = (1,2,3)
a = my_tuple[0]
b = myTuple[2]

Or something like

(a,_,b,_) = myTuple

Is there a way I could unpack the values, but ignore one or more of them of them?


回答1:


Your solution is fine in my opinion. If you really have a problem with assigning _ then you could define a list of indexes and do:

a = (1, 2, 3, 4, 5)
idxs = [0, 3, 4]
a1, b1, c1 = (a[i] for i in idxs)



回答2:


I personally would write:

a, _, b = myTuple

This is a pretty common idiom, so it's widely understood. I find the syntax crystal clear.



来源:https://stackoverflow.com/questions/9532576/ignore-part-of-a-python-tuple

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