簡體   English   中英

這兩個python方法有什么區別?

[英]What is the difference between these two python methods?

我是python新手。

我有一個python方法遞歸地返回列表(以前是string的字典,而s只是前面字典中包含的字符串)

def path(previous, s):
    "Return a list of states that lead to state s, according to the previous dict."
     return [] if (s is None) else path(previous, previous[s]) + [s]

我相信這應該返回相同的結果

def path(previous, s):
    "Return a list of states that lead to state s, according to the previous dict."
    if s is None:
        return []
    else:
        path(previous, previous[s]) + [s]

我期待這兩種方法在功能上完全相同,只是第一種方法更合理。 但是,當我運行第二種方法時,

我收到以下錯誤:

“ TypeError:+不支持的操作數類型:'NoneType'和'list'”

我在這里做錯了什么?

您在第二個方法的else分支中缺少return語句:

def path(previous, s):
    "Return a list of states that lead to state s, according to the previous dict."
    if s is None:
        return []
    else:
        return path(previous, previous[s]) + [s]

第一種方法使用了三元運算符 ,其返回的值(兩個一)被返回return語句,因此,第二需要一個return在兩個分支語句。

暫無
暫無

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

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