[英]Check if value already exists within list of dictionaries and if it does update the counter
這是一個示例字典。 原始字典有更多的鍵。 我沒有包括它們,因為它是不必要的混亂。 這本詞典只是我問題的基本表示。
我有一個字典列表,如下所示:
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}
]
我是一名編程老師,我認為這個問題是一個強調經常被忽視的技術的機會。 您不必更改現有的數據結構,該結構無法有效地查找內容,以便能夠有效地在其中查找內容。 您可以在該結構中構建一個索引,該索引可以有效地查找指向原始結構進行存儲的內容。 這是一種“有你的蛋糕,也有吃它”的情況。 它值得掌握,這樣你就可以把它放在你的技巧包里。
這就像在書的后面維護一個索引,而不是重組書的內容,以便更容易地搜索單個概念,但代價是從頭到尾閱讀的價值降低。 書籍索引同樣可以讓您兩全其美。
您的代碼看起來不錯,只是缺少計數增加的部分。 這是完整的代碼:
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}]
直接(但不是很快)的代碼可能是:
for colour in colours:
for dic in colour_dict:
if dic['main_colour'] == colour:
dic['count'] += 1
break
else:
colour_dict.append({'main_colour': colour, 'count': 1})
結果:
[{'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
循環的else
分支,即如果沒有 break 語句提前完成它。
這是我能想到的最好的方法。 它只對每種顏色的字典列表迭代一次。
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})
如果您以不同的方式構建數據,它將更易於使用。 您還可以查看標准庫的defaultdict
。
from collections import defaultdict
colour_dict = defaultdict(int) # produces int() == 0 on entry creation
colour_dict.update({
'red': 1,
'blue': 5,
'green': 10,
})
colours = ["blue", "blue", "red", "greed", "red", "black"]
for c in colours:
colour_dict[c] += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.