我不明白字典“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}
具体来说,为什么list('list')中的项会用“if item in count”语句添加到dictionary('count')?
===================
“count”字典一开始是空的,没有“append”函数。
这就是它检查
if item in count
的原因,如果这是您第一次看到计数,它将失败(因为它还没有在字典中定义)。你知道吗在这种情况下,它将使用
count[item] = 1
来定义它。你知道吗下一次看到计数时,它已经被定义为1,因此可以使用
count[item] += 1
,即count[item] = count[item] + 1
,即count[item] = 1 + 1
等增加它你可以手动运行你的代码来看看它是如何工作的
遍历列表的第一个元素是1,它会检查此行中的dict,以查看该元素是否添加到dict之前
它不在计数中,因此它将元素放入列表,并在此行中使其值为1
计数变为
然后它遍历下一个元素witch is 2相同的故事计数
下一项是4
下一项是2,在这个例子中,我们的dict中有2,所以在这一行中它的值增加了1
计数变为
它一直持续到列表完成
相关问题 更多 >
编程相关推荐