用列表填充字典

2024-10-01 02:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白字典“count”是如何被“List”填充和引用的。你知道吗

具体来说,为什么list('list')中的项会用“if item in count”语句添加到dictionary('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}


Tags: 函数infordictionaryif字典defcount
3条回答

具体来说,为什么list('list')中的项会用“if item in count”语句添加到dictionary('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`

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

“count”字典一开始是空的,没有“append”函数。

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

这就是它检查if item in count的原因,如果这是您第一次看到计数,它将失败(因为它还没有在字典中定义)。你知道吗

在这种情况下,它将使用count[item] = 1来定义它。你知道吗

下一次看到计数时,它已经被定义为1,因此可以使用count[item] += 1,即count[item] = count[item] + 1,即count[item] = 1 + 1等增加它

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

count = {} // empty dict

遍历列表的第一个元素是1,它会检查此行中的dict,以查看该元素是否添加到dict之前

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

然后它遍历下一个元素witch is 2相同的故事计数

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

下一项是4

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

下一项是2,在这个例子中,我们的dict中有2,所以在这一行中它的值增加了1

     count[item] += 1

计数变为

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

它一直持续到列表完成

相关问题 更多 >