gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:14 24 4
gpt4 key购买 nike

我有两个列表:

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/

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