我可以使用一些幫助來解決這個問題。我需要創建一個函式來創建一個帶有 4 個引數的字典和一個增加該字典每個條目的鍵。到目前為止,我有這個:
def create_db(temp, rain, humidity, wind):
weather = {}
n = 0
for i in (temp, rain, humidity, wind):
n = n 1
weather[n] = (temp, rain, humidity, wind)
return weather
temp = [1, 5, 3]
rain = [0, 30, 100]
humidity = [30, 50, 65]
wind = [3, 5, 7]
weather = create_db(temp, rain, humidity, wind)
print(weather)
這段代碼的問題在于它列印:
{1: (1, 0, 30, 3), 2: (1, 0, 30, 3), 3: (1, 0, 30, 3), 4: (1, 0, 30, 3)}
它只為它們放入串列的第一個值。我究竟做錯了什么?
uj5u.com熱心網友回復:
我要指出的是,雖然您的方法沒有“錯誤”(在應用修復程式之后),但一種更 Pythonic 的方法不需要完全使用索引:
def create_db(temp, rain, humidity, wind):
return {n: vals for n, vals in enumerate(zip(temp, rain, humidity, wind), 1)}
或者更精簡的版本:
def create_db(temp, rain, humidity, wind):
return dict(enumerate(zip(temp, rain, humidity, wind), 1))
uj5u.com熱心網友回復:
溫度,雨等是串列。您需要參考每個串列中的元素 - 即
weather[n] = (temp[n], rain[n], humidity[n], wind[n])
你也不是說for i in (temp, rain, humidity, wind)- 這將是 4,因為那里有 4 個串列變數。而是使用其中一個串列的長度,例如:
for n in range(len(temp)):
這樣你也不需要 increment n。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363168.html
上一篇:如何在Python中的嵌套字典中檢索嵌套字典的深度?
下一篇:如何在字典上對值串列進行排序
