How to ignore the rest of the parameters that return by the function? [duplicate]

柔情痞子 提交于 2021-01-28 05:00:58

问题


def get():
   ...
   ...
   return x,y,z

a,b,c = get()

i don't need b, c is there a solution to ignore them (something like don't care)


回答1:


The recommended way of doing this is to use the _ variable name, as indicated by Abdul Niyas P M, this will not store the values captured by the _.

x, _, z = 1, 2, 3 # if x and z are necessary
# or
x, *_ = 1, 2, 3   # if only x is necessary



回答2:


You might have noticed that if you just do something like a = get() Python will throw all 3 values into the variable 'a' as a tuple.

The best and simplest solution possible at the moment (in the current python version 3.8) is to simply create a second variable to throw stuff in and not ever use that variable. For example:

a, b = get()

However some people like to use a variable named *_ to indicate that this value is trash and needs to be ignored (The variable name adds nothing special, its just a convention to indicate we wont use it source)

a, *_ = get()



回答3:


Let's say, within the returned tuple of values, you are interested only in the k th value.

You could then do:

a = get()[k]

assuming of course, that we're counting k from 0 (and not from 1)



来源:https://stackoverflow.com/questions/65302341/how-to-ignore-the-rest-of-the-parameters-that-return-by-the-function

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