[英]Python count copies in dictionary
我正在数我字典中的副本数。
我的字典
{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 个重复项目。
这是Counter
真正派上用场的地方。 您可以创建一个Counter
来跟踪您的 dict 中的所有值。 这很简单:
from collections import Counter
temp = {0: 'once', 1: 'twice', 2: 'twice'}
counter = Counter (temp.values())
这将返回Counter({'twice': 2, 'once': 1})
。
现在,要找到多少副本,您只需取len (counter)
,所有重复项都是计数(值)> 1 的任何条目(键):
duplicates = [key for key, count in counter.items() if count > 1]
您可以使用copy
模块。
import collections
import copy
cnt = collections.Counter([1,2,3,3,2,4,5,6,7])
def f1(c):
c[2] = 0
tmp = copy.deepcopy(cnt)
f1(tmp)
调用f1
后, cnt
保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.