所以我一直在用 Python 練習一些編碼。我遇到了一項任務,我應該將字典添加到現有串列(有字典)中。
給定的函式(最后)有效,但是當我嘗試撰寫以下內容時(在函式中)
travel_log.append(add_new_country)
代替
travel_log.append(country)
travel_log.append(visits)
travel_log.append(cities)
然后嘗試列印出 travel_log,我會得到以下資訊(查看串列中的最后一個字典):
[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, {'country': 'Germany', 'visits': 5, 'cities': ['Berlin', 'Hamburg', 'Stuttgart']},<function add_new_country at 0x7fefd60e8310>]
有人可以解釋為什么會這樣嗎?
完整代碼:
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
def add_new_country(country,visits,cities):
travel_log.append(country)
travel_log.append(visits)
travel_log.append(cities)
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
uj5u.com熱心網友回復:
您需要創建一個字典并將其添加到travel_log(串列),
def add_new_country(country,visits,cities):
d = {'country': country, 'visits': visits, 'cities': cities}
travel_log.append(d)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515900.html
標籤:Python列表字典
上一篇:如何計算輸入
