python - 将打印的内容添加到字典中

标签 python python-2.7

我有两个列表:

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/

相关文章:

python - 找不到满足要求 tensorflow 的版本

python - Django:尽管引用正确,静态文件仍未显示在网站中

Python 请求 POST 不起作用

python - 在 Python 中创建列表内的列表

python - Pandas :如何从周和年创建日期时间对象?

python - 将 Flask-Assets 与 Flask-Mako 结合使用

python - BeautifulSoup - 抓取后无法创建 csv 和文本文件

python-2.7 - 什么时候使用 zip 而不是 izip 更好?

python - Pygraphviz xlabel 位置和颜色不起作用

python - 在 block 中迭代标准,直到读取 EOF