我有两个列表:
list1 = ['a', 'b', 'c', 'd']
list2 = ['A'. 'B', 'C', 'D']
每次调用我的函数时,我都会打印出每个列表的随机元素:
def whatever():
print 'Element of list 1: ', random.choice(list1), 'Element of list 2: ', random.choice(list2)
我需要将这些打印的元素添加到字典中(我不确定这是否是最佳解决方案),以便跟踪每个元素被打印了多少次,我需要将这个字典保存到持久文件。
这是我需要的:
new_list1 = {} # initially empty
new_list2 = {} # initially empty
在第一次调用我的函数之后:
new_list = {'element4 of list1':1, 'element6 of list2': 1}
每次我调用该函数时,我的 new_list 都会更新并随更新一起保存。 多次调用该函数后:
new_list = {'element1 of list1':1, 'element1 of list2': 1,
'element2 of list1':1, 'element2 of list2': 2,
'element3 of list1':2, 'element3 of list2': 1}
我该怎么做?
提前致谢。
最佳答案
你可以创建一个类来为你做这件事:
from collections import defaultdict
class AutoTrackingDict(dict):
def __init__(self, **kwargs):
super(AutoTrackingDict, self).__init__(**kwargs)
self.counter = defaultdict(int)
def __str__(self):
for key in self.keys():
self.counter[key] += 1
return str(self.counter)
通过重载 __str__
,您可以打印出所有键以及它们被访问的次数。
关于python - 将打印的内容添加到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23160646/