gpt4 book ai didi

Python统计字典中的副本

转载 作者:行者123 更新时间:2023-12-03 08:56:08 24 4
gpt4 key购买 nike

我正在尝试计算字典中的副本。

我的字典

{0: 'once', 1: 'twice', 2: 'twice'}

我的代码:

def count(self, item):
"""Return the number of copies of item in the bag.

Return zero if the item doesn't occur in the bag.
"""

counter = 0
for key in self.bag:
if item == item:
counter = len(self.bag) - 1
else:
counter = 0
print(counter)
return counter

应返回 2,因为有 2 个副本和 1 个重复项。

最佳答案

这就是计数器真正派上用场的地方。您可以创建一个计数器来跟踪字典中的所有值。很简单:

from collections import Counter
temp = {0: 'once', 1: 'twice', 2: 'twice'}
counter = Counter (temp.values())

这将返回 Counter({'twice': 2, 'once': 1})

现在,要查找有多少个副本,您只需使用 len(计数器),所有重复项都是计数(值)> 1 的任何条目(键):

duplicates = [key for key, count in counter.items() if count > 1]

关于Python统计字典中的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55212014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com