我正在尝试遍历列表。但这是第一个要素。它没有得到第二个元素。我不知道我在做什么错。
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']
答案 0 :(得分:3)
使用set
例如:
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)))
输出:
['fingerprint']
['extract']
注意:在迭代对象时删除元素不是一个好习惯。
答案 1 :(得分:0)
只需移除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)
输出:
fingerprint
cipher
filter ['fingerprint']
dupe ['extract']