2017-10-15 64 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