[英]How to get a single output from a function with multiple outputs?
我有以下簡單功能:
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
x = divide(22, 7)
如果我訪問變量x
我得到:
x
Out[139]: (3, 1)
有沒有辦法只得到商或余數?
本質上,您將返回一個元組,這是我們可以索引的可迭代對象,因此在上面的示例中:
print x[0]
將返回商,並且
print x[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
我強烈建議使用后一種形式; 這要簡單得多!
您可以在調用方法時解壓縮返回值:
x, y = divide(22, 7)
或者,您可以僅獲取第一個返回值:
x = divide(22, 7)[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.