我有一个数据结构
info
(一份清单?)我正在构造如下:
pages = [12, 41, 50, 111, 1021, 121]
bookCodes = ['M', 'P', 'A', 'C', 'A', 'M']
sentences = ['THISISASENTENCE',
'ANDHEREISONEMOREEXAMP',
'ALLFROMDIFFERENTBOOKS',
'ANDFROMDIFFERENTPAGES',
'MOSLTYTHESAMELENGTHS',
'THISISSHORT'
]
info = list(zip(bookCodes, pages, sentences))
然后我一次一封信地迭代这个列表(压缩列表)。因为有些句子比其他句子短(例如。
THISISSHORT
)我比其他句子先到达最后一个元素在这种情况下,我希望完全屏蔽这个元素,使其不受未来迭代的影响
但我不想在开始循环之前过滤它
是的。
import random
letters_read = 0
for i in range(21):
random.shuffle(info)
for b, p, s in info:
if len(s) <= i+1:
print("End of sentence reached at position %s. Sentence: %s" % (i, s))
continue
letters_read += 1
我正在使用
continue
跳过这种情况下的元素,并打印一条消息以指示已到达其结尾的句子。但是,这将继续遍历此元素,直到循环结束。
我想从进一步的迭代中排除这些元素。
我有~
10,000
我列表中的句子,它们可以大到
2000
字符,所以我假设通过屏蔽这些句子,而不是跳过,将提高我的脚本的效率。
在迭代过程中是否可以从这个数据结构中删除/屏蔽一个元素?我试过用
info.remove(i)
和
del info[i]
,但这不起作用(因为这不是一个列表)。
输出
以下内容:
End of sentence reached at position 10. Sentence: THISISSHORT
End of sentence reached at position 11. Sentence: THISISSHORT
End of sentence reached at position 12. Sentence: THISISSHORT
End of sentence reached at position 13. Sentence: THISISSHORT
End of sentence reached at position 14. Sentence: THISISASENTENCE
End of sentence reached at position 14. Sentence: THISISSHORT
End of sentence reached at position 15. Sentence: THISISSHORT
End of sentence reached at position 15. Sentence: THISISASENTENCE
End of sentence reached at position 16. Sentence: THISISASENTENCE
End of sentence reached at position 16. Sentence: THISISSHORT
End of sentence reached at position 17. Sentence: THISISASENTENCE
End of sentence reached at position 17. Sentence: THISISSHORT
End of sentence reached at position 18. Sentence: THISISASENTENCE
End of sentence reached at position 18. Sentence: THISISSHORT
End of sentence reached at position 19. Sentence: THISISASENTENCE
End of sentence reached at position 19. Sentence: MOSLTYTHESAMELENGTHS
期望输出
:
End of sentence reached at position 10. Sentence: THISISSHORT
End of sentence reached at position 14. Sentence: THISISASENTENCE
End of sentence reached at position 19. Sentence: MOSLTYTHESAMELENGTHS