2017-10-15 41 views
2

我不明白字典「count」是如何由「List」填充和引用的。使用列表填充字典if語句

具體來說,爲什麼列表('列表')中的項目與「if item in count」語句一起被添加到字典('count')?

'count'字典是空的,並且沒有'append'功能。

這裏是Python功能:

def countDuplicates(List): 
    count = {} 
    for item in List: 
     if item in count: 
      count[item] += 1 
     else: 
      count[item] = 1 
    return count 

print(countDuplicates([1, 2, 4, 3, 2, 2, 5])) 

輸出:{1: 1, 2: 3, 3: 1, 4: 1, 5: 1}

+1

這段代碼有什麼問題嗎?這是你的代碼嗎? –

+0

歡迎來到SO。請花時間閱讀[問]及其中包含的鏈接。您可能還需要投入一些時間來完成[教程](https://docs.python.org/3/tutorial/index.html)。 – wwii

+0

我認爲這個問題很明顯。第二段詢問'in'的作用,第三段詢問如何在沒有'append'的情況下將內容添加到'dict'中。 – luther

回答

1

這就是爲什麼它會檢查if item in count,如果這是你第一次看到計數(因爲它贏得了」將失敗在字典中尚未定義)。

在這種情況下,它將使用count[item] = 1來定義它。

下一次計數看到,它會已確定,(爲1),所以你可以使用它count[item] += 1,即count[item] = count[item] + 1,即count[item] = 1 + 1增加等

+1

謝謝!現在它是有道理的!第一次遇到「來自計數的項目」時,第一次失敗,並且首次遇到來自列表的唯一項目時,將[計數]與列表中的'項目'一起分配給'else:count [item]'。 – neighbornate

2

你可以手工運行代碼看看它是如何工作

count = {} // empty dict 

迭代通過列表第一個元素是1它將檢查字典在此行中看到的是這個元素添加到字典

if item in count: 

它不是在數量,使得它把該元素添加到列表中,並使其價值1在此行

count[item] = 1 //This appends the item to the dict as a key and puts value of 1 

計數變成

count ={{1:1}} 

然後通過下一個元素女巫迭代是2相同故事計數變成

count={{1:1},{2:1}} 

下一個項目是4

count = {{1:1},{2:1},{4,1}} 

下一個項目是在這種情況下,2,我們有2個在我們的字典所以它在這條線增加了它的值由1

 count[item] += 1 

計數變成

count = {{1:1},{2:2},{4,1}} 

並繼續直到列表已完成

+0

謝謝@Alper First Kaya!這正是我正在尋找的解釋/步驟! – neighbornate

+0

我想告訴你的是,你並不孤單:P'from collections import Counter; duplicateates = Counter([1,2,4,3,2,2,5])https://docs.python.org/2/library/collections.html#collections.Counter – slackmart

+0

謝謝@slackmart。 '收藏'圖書館在這種情況下也一定會起作用。我發佈了這個問題,以理解從列表中將項目分配到帶有if語句的字典中。絕對重要,但是這是一個值得的編程課程。 – neighbornate

0

具體來說,爲什麼列表('列表')中的項目與「if item in count」語句一起被添加到字典('count')?


`checking if the element already added in to dictionary, if existing increment the value associated with item. 
Example: 
[1,2,4,3,2,2,5] 
dict[item] = 1 value is '1'--> Else block, key '1'(item) is not there in the dict, add to and increment the occurrence by '1'

when the element in list[1,2,4,3,2,2,5] is already present in the dict count[item] += 1 --> increment the occurrence against each item`

=================

「計數」字典是空的,開始有和沒有「附加」功能。

 
append functionality not supported for empty dict and can be achieved by 
count[item] += 1