我有一個包含字典的串列 - 我想要一個從該串列中的字典回傳鍵值的函式。說明如下。
下面的函式simulate_tournament將一個串列作為輸入,并且應該通過索引回傳一個字串(不是串列/字典)。
當我嘗試使用 獲取我需要的回傳值(一個字串,它是串列中 dict 的鍵值)時return teams[0]['teams'],我無法做到。錯誤:TypeError: string indices must be integers。有了return teams,我得到了包含 dict 的串列,這對我有用但不可取。
def simulate_tournament(teams):
"""Simulate a tournament. Return name of winning team."""
teams = simulate_round(teams)
if (len(teams) != 1):
teams = simulate_tournament(teams)
return teams[0]["team"]
但是,當我將代碼更改為以下代碼時,我能夠以某種方式準確地獲得我需要的回傳值。沒有錯誤。
def simulate_tournament(teams):
"""Simulate a tournament. Return name of winning team."""
while (len(teams) > 1):
teams = simulate_round(teams)
return teams[0]["team"]
我在這里錯過了什么,我在這個函式的第一個版本而不是第二個版本中得到了一個錯誤?
uj5u.com熱心網友回復:
您的第一個函式將teams- 字典串列 - 作為引數并回傳團隊名稱。所以下面一行:
teams = simulate_tournament(teams)
沒有意義,因為您正在用包含團隊名稱的字串替換您的字典串列。這就是為什么
teams[0]["team"]
產生錯誤。
要遞回地使用該函式,它必須回傳它作為引數接受的相同型別的資料。對于遞回函式來說,這似乎不是一個好的用例——它會造成混亂,并且無法實作你無法通過回圈輕松完成的任何事情——所以你的第二種方法更好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525698.html
標籤:Python列表字典递归
