簡體   English   中英

如何從具有多個輸出的函數中獲取單個輸出?

[英]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]將返回余數

您有兩種廣泛的選擇:

  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)) 
  2. 保留該函數不變,但顯式忽略其中一個返回值:

     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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM