我通過字典迭代,如果某些條件匹配,則刪除字典項目。現在字典動態索引得到更新。在刪除項目後堅持字典索引
例如
{u'Titanic': {'match': [{'category': u'Book'},
{'category': u'Movie'},
{'category': u'Product'}],
'score': 100}}
雖然迭代match
,如果我刪除Book
(指數 - 0),所以現在下一個迭代過程中它顯示我product
(指數 - 1)直接,考慮到指數0 movie
。它考慮已經迭代的索引-0。
代碼剪斷:
for k1,v1 in enumerate(value['match']):
if k1 != '':
print '\n Category: ',k1,' ',v1['category']
print 'Do you want to change the class of entity',k1 ,'? Y/N', 'Or delete', k1, '1/0'
choice = raw_input()
if choice == 'N' or choice == 'n':
pass
elif choice == 'Y' or choice == 'y' :
print '\tEnter class : \t'
v1['category'] = raw_input()
tagged = string.replace(sentence, key, v1['category'])
tagged_ans.append(tagged)
elif choice == '1':
del v1['category']
del value['match'][k1]
在這種情況下如何保持當前索引和不跳過任何項的迭代。在上面的示例中movie
可以跳過
你真正的問題是什麼? – 2014-11-24 07:09:30
@RikVerbeek:對不起,更新了問題 – puncrazy 2014-11-24 07:16:51
不要刪除字典中的鍵,你正在更新字典並同時增加計數器,這就是爲什麼指針在第二次迭代中移動到第三項的原因。 – 2014-11-24 07:38:28