Python 如何基于条件解析字典值
我的字典是这样的:Python 如何基于条件解析字典值,python,dictionary,Python,Dictionary,我的字典是这样的: {'0': 'correct g', '1': 'correct g', '2': 'incorrect ng', '3': 'correct g', '4': 'correct g', '5': 'incorrect g', '6': 'incorrect ng'} 我想在不正确的ng之后识别连续的值,这些值等于正确的g,并返回相应的键 所以输出看起来像 {2: [3,4]} 其中2是不正确ng的键,值列表是连续的键,其值等于正确g 要识别不正确的ng,我有
{'0': 'correct g',
'1': 'correct g',
'2': 'incorrect ng',
'3': 'correct g',
'4': 'correct g',
'5': 'incorrect g',
'6': 'incorrect ng'}
我想在不正确的ng
之后识别连续的值,这些值等于正确的g
,并返回相应的键
所以输出看起来像
{2: [3,4]}
其中2是不正确ng
的键,值列表是连续的键,其值等于正确g
要识别不正确的ng
,我有:
{k:v for k,v in dictionary.items() if v == 'incorrect ng'}
但我不知道如何才能继续向下移动这些值,直到我碰到另一个
错误的ng
。有什么建议吗?假设每个项目都有一个数字键,并且没有间隙,您可以像这样迭代项目:
newDict = {}
Arr = []
num = -1
start = False
for key in dictionary:
value = dictionary[key]
if value == 'incorrect ng' and start == False:
num = int(key)
start = True
elif value == 'incorrect ng' and start == True:
start = False
elif value == 'correct g' and start == True:
Arr.append(key)
if num != -1:
newDict[int(num)] = Arr
print(newDict)
answer = {}
for key in range(len(dictionary)):
if dictionary[key] == 'incorrect ng':
answer[key] = []
for next_key in range(key, len(dictionary)):
if dictionary[next_key] == 'correct g':
answer[key].append(next_key)
else:
break
当您得到第一个
'error ng'
时,只需跟踪其键值,然后查看接下来的几个条目,直到找到一个不是'correct g'的条目。请注意,默认情况下,python 2.7中的字典不保留顺序。因此,使用OrderedDict
来保持秩序,或者简单地使用列表
from collections import OrderedDict, defaultdict
values = OrderedDict()
values['0'] = 'correct g'
values['1'] = 'correct g'
values['2'] = 'incorrect ng'
values['3'] = 'correct g'
values['4'] = 'correct g'
values['5'] = 'incorrect g'
values['6'] = 'incorrect ng'
results = defaultdict(list)
new_key = None
for key in values:
# when we encounter 'incorrect ng' we will set it as new_key.
if values[key] == 'incorrect ng':
new_key = key
elif values[key] == 'correct g' and new_key:
# if new_key is present and current value is 'correct g'
results[new_key].append(key)
else:
# any other key value comes in between then we clear the new_key
# remove this piece of code if intermediate values could be 'correct ng' or other things.
new_key = None
results
输出:
defaultdict(list, {'2': ['3', '4']})
字典是无序的。你可能想考虑一个不同的数据结构,这就是为什么我选择把我的数据表示为数字键的原因,所以它们像Hamms指出的那样保持有序,你的要求没有多大意义,因为字典是非有序的数据结构。顺序是随机变化的。第一次访问词典时,两个不正确的g
之间可能有三个正确的g
,下一次则没有。考虑使用<代码>集合。OrrordDigt < /Cord>。使用数字键的“E9E9S”不会改变字典是非有序数据结构的事实。我认为OP只关心两个代码之间的<代码>正确的G<代码>。因此,要访问数据,OP必须对键进行排序,然后按顺序访问字典条目。