我是 python 新手。我在學習字典時遇到了這個代碼。我不明白的一件事是 how counts,它僅在第一行中宣告為字典,在 if 陳述句中用于在沒有添加任何值時在其中搜索名稱。
counts = dict()
names = ['csev' , 'cwen' , 'csev' , 'zqian' , 'cwen' ]
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] 1
print(counts) # typo
uj5u.com熱心網友回復:
如果您可以在這個平臺上嘗試 - https://pythontutor.com/ 您可以看到執行的每個步驟中發生了什么。但這里有一個簡單的解釋。
counts = dict() #
names = ['csev' , 'cwen' , 'csev' , 'zqian' , 'cwen' ]
for name in names: # looping each name in the list
if name not in counts: # check if it in the dict. counts (by key)
counts[name] = 1 # if not, add it, and value set to 1 initially
else:
counts[name] = counts[name] 1 # if existing, add value 1
print(count)
輸出
{'csev': 2, 'cwen': 2, 'zqian': 1}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490574.html
