我正在遍历一个数据库列
我需要创建一个字典,如果满足条件,它会更新某些键的某些值
比如说
The first iteration is: 'apples'
The dictionary should be {'apples': 1}
The second iteration is: 'peers'
The dictionary should be {'apples': 1, 'peers': 1}
The third iteration is: 'apples'
The dictionary should be {'apples': 2, 'peers': 1}
我为基本的解释道歉。这是(我认为)传达我想要的东西的最好方式,因为我不知道如何编写代码
我需要将其放在字典中,因为此操作深入到嵌套for循环结构中
目标是:
就是得到最容易出现的迭代
预期结果:
mostListed = 'apples'
我是python新手,如果我遗漏了一些明显的东西,我会非常乐于学习
使用来自
collections
的Counter()
:例如,使其适用于您的案例:
为了清晰起见,在已有众多答案的基础上增加了这一点
无违约地
您可以使用以下代码:
输出:
使用defaultdict
您可以创建一个默认值为
0
的defaultdict
,如下所示:输出
相关问题 更多 >
编程相关推荐