如何从具有多个输出的函数中获取单个输出?
问题内容:
我有以下简单功能:
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
x = divide(22, 7)
如果我访问变量,则会x
得到:
x
Out[139]: (3, 1)
有没有办法只得到商 或 余数?
问题答案:
您有两种主要选择:
-
修改该函数以适当返回一个或两个,例如:
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))
-
保留该函数不变,但显式忽略其中一个返回值:
quot, _ = divide(x, y) # assign one to _, which means ignore by convention
rem = divide(x, y)[1] # select one by index
我强烈建议使用后一种说法;这 要 简单得多!