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)]
然而,这段代码似乎没有完成任务。知道怎么修吗?谢谢!
最佳答案
当您使用for
迭代列表时,尝试修改列表是很危险的。你真正想要的是一个while循环:
contrived_data = [[(1, 1, 1), ('hello', 'bar')], [(222, 3, 4), ('norweigan', 'blue')], [('anthrax', 'ripple'), (42, 'life')]]
looking_for = (1, 'life')
index = 0
while index < len(contrived_data):
for two_pull in contrived_data[index]:
for item in looking_for:
if item in two_pull:
print(contrived_data.pop(index))
index -= 1
break # Only jumps out of the innermost loop
index += 1
对于更大的数据集,这应该比复制原始列表更有效。
关于python - Python:搜索元组列表,删除整个索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11766161/