我想比較兩個列表(預期和實際)。我想檢查預期列表項目是否存在於實際列表項目中。我正在嘗試下面的示例代碼。我可以嘗試set(expected)-set(actual)
。這會給我不同,但我想檢查項目是否存在,否則顯示哪些項目不存在。可以有人指導我,如何實現低於預期的結果或我正在做什麼錯誤。如果我是學習者,請忽略是否有錯誤。如何檢查列表項是否存在於另一個列表中
actual = ['resources.sh', 'server.properties', 'resources.csv', 'resources.log', 'sampleresources.csv']
expected = ['resources.sh', 'server.properties', 'resources.csv', 'resources.log']
for i in expected:
for b in actual:
if b.split(".")[0] in i:
print "{} is present".format(b)
else:
print "{} is not present".format(i)
實際結果:
resources.sh is present
resources.sh is not present
resources.csv is present
resources.log is present
resources.sh is not present
server.properties is not present
server.properties is present
server.properties is not present
server.properties is not present
server.properties is not present
resources.sh is present
resources.csv is not present
resources.csv is present
resources.log is present
resources.csv is not present
resources.sh is present
resources.log is not present
resources.csv is present
resources.log is present
resources.log is not present
預期結果:
resources.sh is present
server.properties is present
resources.csv is present
resources.log is present
sampleresources.csv is not present
你'set.intersection'後? –
謝謝@JonClements。這是正確的做法嗎?如果len(set(expected).intersection(set(actual)))> 0: print True else: print False ' – Madhu