簡體   English   中英

函數返回返回int或int列表。 將第一個與變量相關聯

[英]Function returns returns either int or list of ints. Assinging the first to a variable

假設我們有

def f_1():
    return (3, 4)

def f_2():
    return 2

給出了功能。 我無法修改的代碼。 我們知道它們返回的是整數或序列。

我想將return分配給一個變量,如果return是它們的序列,則該變量應僅取整數的第一個。

Python中是否有內置語法設備可讓我執行此操作?

for function in [f_1, f_2]:
    ...
    x = function()[0] # Works for f_1, breaks for f_2
    y = function()    # Works for f_2, assigns (3, 4) for f_1 while 
                      #   we really would like only the 3 to be the 
                      #   assigned value

注意:假設我們不知道哪個函數返回序列,哪個函數僅返回數字。

有內置的句法設備嗎

不,通常的做法是請求 寬恕

x = function()
try:
    x = x[0]
except TypeError:
    pass

我不會去嘗試-除外聲明。 對我來說,這太過分了。

我更有可能嘗試執行以下操作:

result = function()
# this can be changed to abc.Sequence for more general approach
if isinstance(result, (list, tuple)): 
    result = result[0]

在另一個方向上,將f_2包裝在另一個函數中,以確保在循環主體中調用的函數始終返回序列。

for function in [f_1, lambda : (f_2(),)]:
    x = function()[0]

另一個函數調用的額外開銷可能會使這種方法不受歡迎。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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