Possible Duplicate:
Remove items from a list while iterating in Python
我有一个相当嵌入的列表:具体来说,它是元组列表的列表。为了简单起见,整个列表是一个句子列表。在每个句子中,每个单词都被放入一个元组中,其中包含有关该单词的信息。每个句子中的最后一个元组包含有关说话者的信息,但如果需要,可以将其删除。
我想搜索这些元组,如果找到某个值,则删除整个句子。
这是一个示例列表:
sentenceList = [[('the', 'det', '1|2|DET'), ('duck', 'n', '2|3|SUBJ'), ('xxx', 'unk', '3|0|ROOT'), ('*MOT', 373)],
[('yyy', 'unk', '1|0|ROOT'), ('*CHI', 375)],
[('what', 'pro', '1|2|OBJ'), ('happen-PAST', 'v', '2|0|ROOT'), ('to', 'prep', '3|2|JCT'), ('the', 'det', '4|5|DET'), ('duck', 'n', '5|3|POBJ'), ('*MOT', 378)],
[('boom', 'int', '1|0|ROOT'), ('*CHI', 379)]]
如果一个句子包含 'xxx'
或'yyy'
,我想删除整个句子。我尝试过的代码是:
wordList = ['xxx','yyy']
for sentence in sentenceList:
for wordTuple in sentence:
for entry in wordTuple:
if entry in wordList:
del sentence
这应该删除整个句子,即:
[('the', 'det', '1|2|DET'), ('duck', 'n', '2|3|SUBJ'), ('xxx', 'unk', '3|0|ROOT'), ('*MOT', 373)], [('yyy', 'unk', '1|0|ROOT'), ('*CHI', 375)]
但是,这段代码似乎没有完成任务。知道如何修复它吗?谢谢!
最佳答案
wordList = set(('xxx','yyy'))
for sentence in sentenceList[:]:
removed = False
for wordTuple in sentence:
for entry in wordTuple:
if entry in wordList:
sentenceList.remove(sentence)
removed = True
break
# end of if
# end for each entry
if removed:
break
# end for each word tuple
# end for each sentence
注释:
- 迭代列表的(浅)副本,以避免因修改正在遍历的集合而出现错误
- 从列表中删除对象,而不是简单地从本地命名空间中删除变量名
- 这对于大型数据集效率不高
关于Python:搜索元组列表,删除整个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11766161/