这是一本示例词典。原来的字典有更多的键。我没有把它们包括在内,因为这是不必要的杂乱。这本词典只是我问题的基本描述
我有一个字典列表,如下所示:
colour_dict = [
{'main_colour': 'red', 'count': 1},
{'main_colour': 'blue', 'count': 5},
{'main_colour': 'green', 'count': 10},
]
以及颜色列表,如下所示:
colours = ["blue", "blue", "red", "greed", "red", "black"]
当我反复浏览颜色列表时,我想检查颜色列表中的颜色是否已经存在于字典列表中。如果确实存在,则将计数增加1,如果不存在,则将其添加到字典中
到目前为止,我得到的是:
for colour in colours:
if any(d['main_colour'] == colour for d in colour_dict):
#Increase counter of that colour
else:
colour_dict.append({
'main_colour': colour, 'count': 1
})
您的代码看起来不错,只是缺少计数增加的部分。以下是完整的代码:
给定数据的结果:
如果您需要以显示的格式显示数据,并且不希望为每次添加都重复该列表,那么这不是问题。您所要做的就是为该数据结构构建一个索引。索引将是一个地图,其中的键是颜色,值是原始结构中该颜色的索引。首先构建这个索引,然后使用它高效地处理新条目。事情是这样的:
结果:
我是一名编程老师,我认为这个问题是一个强调一个经常被忽视的技术的机会。您不必更改现有的数据结构,因为这些数据结构在查找内容时效率不高,所以您可以高效地在其中查找内容。您可以在该结构中构建一个索引,以便高效地查找指向原始存储结构的内容。这是一种“吃你的蛋糕,也吃它”的情况。它值得一抓,这样你就可以把它放在你的魔术袋里了
这就像是在一本书的后面保留一个索引,而不是重新构造书的内容,以便更容易地搜索单个概念,而代价是使其前后阅读的价值降低。图书索引同样能让你两全其美
这是我能想到的最好的了。每种颜色只在字典列表上迭代一次
相关问题 更多 >
编程相关推荐