如何从具有多个输出的函数中获取单个输出? [英] How to get a single output from a function with multiple outputs?

查看:129
本文介绍了如何从具有多个输出的函数中获取单个输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单功能:

def divide(x, y):
    quotient = x/y
    remainder = x % y
    return quotient, remainder  

x = divide(22, 7)

如果我访问变量x,我得到:

If I accesss the variable x I get:

x
Out[139]: (3, 1)

有没有办法只得到商的余数?

Is there a way to get only the quotient or the remainder?

推荐答案

您有两个广泛的选择,或者:

You have two broad options, either:

  1. 修改该函数以适当地返回一个或两个,例如:

  1. Modify the function to return either or both as appropriate, for example:

def divide(x, y, output=(True, True)):
    quot, rem = x // y, x % y
    if all(output):
        return quot, rem
    elif output[0]:
        return quot
    return rem

quot = divide(x, y, (True, False))

  • 函数保持不变,但显式忽略返回值中的一个或另一个:

  • Leave the function as it is, but explicitly ignore one or the other of the returned values:

    quot, _ = divide(x, y)  # assign one to _, which means ignore by convention
    rem = divide(x, y)[1]  # select one by index
    

  • 我强烈建议使用后一种说法; 更简单

    I would strongly recommend one of the latter formulations; it's much simpler!

    这篇关于如何从具有多个输出的函数中获取单个输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆