下面的for循環輸出代碼:需要幫助理解這個字典
def list_to_dict(li):
dct = {}
for item in li:
dct[item] = dct.get(item,0)+1
print(dct)
return dct
li = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 7]
print(list_to_dict(li))
下面是輸出。我無法理解,輸出是如何來的?
{1: 1}
{1: 2}
{1: 3}
{1: 3, 2: 1}
{1: 3, 2: 1, 3: 1}
{1: 3, 2: 1, 3: 2}
{1: 3, 2: 1, 3: 2, 4: 1}
{1: 3, 2: 1, 3: 2, 4: 2}
{1: 3, 2: 1, 3: 2, 4: 3}
{1: 3, 2: 1, 3: 2, 4: 4}
{1: 3, 2: 1, 3: 2, 4: 5}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1, 7: 1}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1, 7: 2}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1, 7: 2}
您是否意識到'dictionaries' **不能**有重複鍵? –
這將對列表中的項目進行計數。什麼,*完全*你不明白?你必須對你的問題具體。 –
'進口收藏品; ([1,1,1,2,3,3,4,4,4,4,5,5,6,7,7]);以及[ 'Out [..]:Counter({1:3,2:1,3:2,4:5,5:1,6:1,7:2}) –