1 回答
TA贡献2019条经验 获得超9个赞
我做出以下假设,
您只想将 计数添加到值中
(1,1)
OrderedDict
您不希望创建覆盖当前 .
OrderedDict
您可以修改原始词典
现在,根据问题中提供的信息和上述假设,一种可能的解决方案是将每个值替换为包含两个元素的列表,即'[原始值,(1,1)的计数]。
from collections import OrderedDict
odict_items = [(3, [(0, 1), (1, 1), (1, 1)]),
(11, [(0, 0), (1, 1), (1, 1)]),
(12, [(0, 0), (1, 1), (1, 1)])]
my_odict = OrderedDict()
for item in odict_items:
k, v = item
my_odict[k] = v
现在计算每个值中出现的次数,并相应地更新值(1,1)
pattern_to_find = (1, 1)
for key, value in my_odict.items():
tuple_count = value.count(pattern_to_find)
new_value = [value, tuple_count]
my_odict[key] = new_value
现在字典有以下内容:
OrderedDict([(3, [[(0, 1), (1, 1), (1, 1)], 2]),
(11, [[(0, 0), (1, 1), (1, 1)], 2]),
(12, [[(0, 0), (1, 1), (1, 1)], 2])])
现在,您可以创建其他函数以仅访问值或元组计数
# Returns the count of (1, 1) only
def get_count(my_dict, key):
return my_dict[key][1]
# Return the original value only
def get_tuple(my_dict, key):
return my_dict[key][0]
所以你可以像这样使用它们
print(my_odict[3])
# [[(0, 1), (1, 1), (1, 1)], 2]
print(get_count(my_odict,3))
# 2
print(get_tuple(my_odict, 3))
# [(0, 1), (1, 1), (1, 1)]
添加回答
举报