检查字典列表中是否已经存在该值,以及它是否更新了计数器

2024-09-22 20:37:53 发布

您现在位置: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"]

当我反复浏览颜色列表时,我想检查颜色列表中的颜色是否已经存在于字典列表中。如果确实存在,则将计数增加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
        })

Tags: in示例列表for字典颜色maincount
3条回答

您的代码看起来不错,只是缺少计数增加的部分。以下是完整的代码:

for colour in colours:
    if any(d['main_colour'] == colour for d in colour_dict):
        for i in range(len(colour_dict)):
            if colour in colour_dict[i].values():
                colour_dict[i]['count']+=1
    else:
        colour_dict.append({
            'main_colour': colour, 'count': 1
        })

给定数据的结果:

>>> 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}]

如果您需要以显示的格式显示数据,并且不希望为每次添加都重复该列表,那么这不是问题。您所要做的就是为该数据结构构建一个索引。索引将是一个地图,其中的键是颜色,值是原始结构中该颜色的索引。首先构建这个索引,然后使用它高效地处理新条目。事情是这样的:

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}
]

我是一名编程老师,我认为这个问题是一个强调一个经常被忽视的技术的机会。您不必更改现有的数据结构,因为这些数据结构在查找内容时效率不高,所以您可以高效地在其中查找内容。您可以在该结构中构建一个索引,以便高效地查找指向原始存储结构的内容。这是一种“吃你的蛋糕,也吃它”的情况。它值得一抓,这样你就可以把它放在你的魔术袋里了

这就像是在一本书的后面保留一个索引,而不是重新构造书的内容,以便更容易地搜索单个概念,而代价是使其前后阅读的价值降低。图书索引同样能让你两全其美

这是我能想到的最好的了。每种颜色只在字典列表上迭代一次

for colour in colours:
    c_dict = list(filter(lambda c: c['main_colour']==colour, colour_dict))

    # if it exists c_dict points at the actual value within the colour_dict list
    # This means c_dict can be simply updated
    if len(c_dict) != 0:
        c_dict[0]['count'] += 1
    else:
        colour_dict.append({'main_colour':colour, 'count':1})

相关问题 更多 >