def data_change(account):
data_name = data["name"]
data_desc = data["description"]
data_country = data["country"]
return f"{data_name}, is a {data_desc}, from {data_country}"
print(f"option A : {data_change(data_a)}")
上面的代碼是我要處理的資料以顯示隨機資料。下面的串列字典是前 2 個示例資料
data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
}]
并且錯誤顯示是 TypeError: list indices must be integers or slices, not str
上線:data_name = data["name"]
是的,我搜索了許多解決方案,但沒有解決我的問題。
喜歡這個鏈接
https://www.learndatasci.com/solutions/python-typeerror-list-indices-must-be-integers-or-slices-not-str/#:~:text=This type error occurs when,使用 the int() function。
如果你想要完整的代碼檔案,可以問我。這是一項正在進行的作業
uj5u.com熱心網友回復:
資料是一個串列而不是字典,因此您使用從零開始的索引來列舉串列中的專案。您可以通過這樣的 for 回圈列舉專案:
def data_change(data):
ans = []
for account in data:
data_name = account["name"]
data_desc = account["description"]
data_country = account["country"]
ans.append(f"{data_name}, is a {data_desc}, from {data_country}")
return "\n".join(ans)
uj5u.com熱心網友回復:
您的變數“資料”是一個包含兩個字典的串列。使用“data_name = data["name"]”,您嘗試訪問此串列,但“name”不是整數,因此您會收到 TypeError。您的串列只有兩個條目,因此您可以使用 data[0]["name"] 或 data[1]["name"] 訪問它。
編輯:正如 Mazimia 所說,遍歷串列中的 dicts 似乎是個好主意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492328.html
