【发布时间】:2019-05-14 08:00:02
【问题描述】:
我正在尝试遍历列表。但它正在获得第一个元素。它没有得到第二个元素。我无法弄清楚我做错了什么。
filte = ['fingerprint','cipher']
dupe = ['cipher','extract']
for val in filte:
print(val)
if val in dupe:
dupe.remove(val)
else:
filte.remove(val)
print("filter",filte)
print("dupe",dupe)
我得到的输出:
fingerprint
filter ['cipher']
dupe ['cipher', 'extract']
需要的输出:
fingerprint
cipher
filter ['cipher']
dupe [ 'extract']
【问题讨论】:
-
我不完全知道循环在 Python 中是如何工作的,但是当您在循环期间删除一个元素时,它可能会带来一个迭代问题。它正在等待第二个元素,但删除后,
cipher成为第一个元素,因此没有第二个。 -
没错。所以 OP 你想要么迭代一个反向列表(删除它的最后一个元素不会改变它的索引),要么构建一个新列表,在其中添加合适的元素。
-
你能解释一下@SmackAlpha你想在这里做什么吗?
标签: python-3.x list for-loop