使用列表 if 语句填充字典



我不明白字典"count"是如何被"List"填充和引用的。

具体来说,为什么列表中的项目("列表")会使用"if 项目在计数"语句中添加到字典("计数")中?

"

计数"字典一开始是空的,没有"追加"功能。

这是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}

你可以手动运行你的代码,看看它是如何工作的

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}}

并一直持续到列表完成

这就是为什么

它会检查if item in count,如果这是您第一次看到计数,这将失败(因为它尚未在字典中定义)。

在这种情况下,它将使用 count[item] = 1 .

下次看到计数时,它已经被定义(作为 1),因此您可以使用 count[item] += 1 递增它,即 count[item] = count[item] + 1,即 count[item] = 1 + 1等。

具体来说,为什么列表中的项目("列表")会使用"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`

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

The 'count' dictionary is empty to begin with and there is no 'append' function.

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

最新更新