简体   繁体   English

for循环不会循环到下一个元素python

[英]for loop doesn't loop to next element python

I am trying to loop through a list. 我试图遍历列表。 But it is getting the first element. 但这是第一个要素。 It doesn't gets the second element. 它没有得到第二个元素。 I can't figure out what i am doing wrong. 我不知道我在做什么错。

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)

output i got: 我得到的输出:

fingerprint
filter ['cipher']
dupe ['cipher', 'extract']

required output: 所需的输出:

fingerprint
cipher
filter ['cipher']
dupe [ 'extract']

Use set 使用set

Ex: 例如:

filte = ['fingerprint','cipher']
dupe = ['cipher','extract']

print(list(set(filte) - set(dupe)))  #OR list(set(filte).difference(set(dupe)))
print(list(set(dupe) - set(filte)))

Output: 输出:

['fingerprint']
['extract']

Note: Not a good practice to remove elements while iterating the object. 注意:在迭代对象时删除元素不是一个好习惯。

just remove the else 只是删除else

filte = ['fingerprint','cipher']
dupe = ['cipher','extract']

for val in filte:
    print(val)
    if val in dupe:
        dupe.remove(val)
        filte.remove(val)

print("filter",filte)
print("dupe",dupe)

output: 输出:

fingerprint
cipher
filter ['fingerprint']
dupe ['extract']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM