[英]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.