简体   繁体   English

如何从函数中获取特定值?

[英]How can I get a specific value from function?

So my question is: if I have a function that looks like this:所以我的问题是:如果我有一个看起来像这样的函数:

def function():
    x = 2 + 3
    y = x + 2
    return x, y

And I need to use an x from this function, but I don't need the y.我需要使用这个函数中的 x,但我不需要 y。 How can I choose which value it returns.我如何选择它返回的值。

PS.附注。 I can't change the code in the first function我无法更改第一个函数中的代码

Thanks for help!感谢帮助!

If you can't modify the function, it will always return both.如果您不能修改该函数,它将始终返回两者。 But if you're interested in only x , you can assign the output tuple to two separate variables, and essentially ignore the y argument by assigning it to an arbitrary variable and forget about it但是,如果您只对x感兴趣,则可以将输出元组分配给两个单独的变量,并通过将其分配给任意变量来基本上忽略y参数并忘记它

x, _ = function()

>>> print(x)
5

Another way would be to select only the first value in the tuple:另一种方法是只选择元组中的第一个值:

x = function()[0]

for example if you need the y, you can do this:例如,如果您需要 y,您可以这样做:

_, y = function()

or to get x:或得到 x:

x, _ = function()
def function():
    x = 2 + 3
    y = x + 2
    return x, y

x, y = function()

print(x)

Hope that solved your problem希望解决了你的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM