python - 检查字典列表中是否已经存在值以及它是否更新了计数器
问题描述
这是一个示例字典。原始字典有更多键。我没有包括它们,因为它是不必要的混乱。这本词典只是我的问题的基本表示。
我有一个字典列表,如下:
colour_dict = [
{'main_colour': 'red', 'count': 1},
{'main_colour': 'blue', 'count': 5},
{'main_colour': 'green', 'count': 10},
]
和颜色列表,如下:
colours = ["blue", "blue", "red", "greed", "red", "black"]
当我遍历颜色列表时,我想检查颜色列表中的颜色是否已经存在于字典列表中colour_dict
。如果它确实存在,则将计数增加 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
})
解决方案
如果您需要您的数据采用您显示的格式,并且不想为每次添加而产生迭代该列表的成本,那不是问题。您所要做的就是为该数据结构建立一个索引。索引将是一个映射,其键是颜色,值是原始结构中该颜色的索引。您首先构建此索引,然后使用它有效地处理新条目。这是怎么回事:
colour_dict = [
{'main_colour': 'red', 'count': 1},
{'main_colour': 'blue', 'count': 5},
{'main_colour': 'green', 'count': 10},
]
colours = ["blue", "blue", "red", "greed", "red", "black"]
# Build an index mapping colors to positions in the 'colour_dict' list
index = {}
for i, entry in enumerate(colour_dict):
index[entry['main_colour']] = i
# Iterate over the new values, tallying them in the original structure, and
# adding new entries to both the original structure and the index when
# we discover colors that aren't yet in our structure. Note that there
# is just a single lookup per addition to the structure. No per-addition
# iteration here.
for colour in colours:
if colour in index:
colour_dict[index[colour]]['count'] += 1
else:
index[colour] = len(colour_dict)
colour_dict.append({'main_colour': colour, 'count': 1})
# Show the updated original structure
print(colour_dict)
结果:
[
{'main_colour': 'red', 'count': 3},
{'main_colour': 'blue', 'count': 7},
{'main_colour': 'green', 'count': 10},
{'main_colour': 'greed', 'count': 1},
{'main_colour': 'black', 'count': 1}
]
我是一名编程老师,我认为这个问题是一个突出经常被忽视的技术的机会。您不必更改现有的查找内容效率不高的数据结构,以便能够有效地在其中查找内容。您可以在该结构中构建一个索引,该索引可以有效地查找指向原始结构的内容以进行存储。这是一种“有你的蛋糕,也吃它”的情况。它值得抓住,这样你就可以把它放在你的技巧包里。
这就像在书的后面维护一个索引,而不是重组书的内容,以便更容易搜索单个概念,代价是降低从前到后阅读的价值。图书索引同样可以为您提供两全其美的体验。
推荐阅读
- python - 让 imagenet 模型 pnasnet_large 与 hub.KerasLayer 一起使用
- macos - 如何在 Mac 上使用 Preview 裁剪 PDF 文件中的空白区域?
- wordpress - 允许使用空购物车进行 Woocommerce 结帐?
- c# - 两个对象集合之间有争议的并行工作
- flowtype - 无法调用 `this.state.quantities.flatMap`,因为 `Array` 中缺少属性 `flatMap`
- google-apps-script - 在 Google 表格中归档一行时如何添加新行
- odbc - 从“Aginity Workbench for Redshift”工具连接到 AWS Redshift 集群时出现连接错误
- reactjs - react中的样式化组件
- html - 我的媒体查询在 CSS 中不起作用,似乎无法识别
- kubernetes - 如何从需要模板化的文件目录生成配置映射?