簡體   English   中英

如何檢查列表項是否在另一個列表中

[英]How to check if list item is present on another list

我正在嘗試比較兩個列表(預期列表和實際列表)。 我想檢查實際的列表項中是否存在預期的列表項。 我正在嘗試以下示例代碼。 我可以嘗試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

您可以只遍歷actual一次:

for i in actual:
     if i in expected:
         print(i, "is present")
     else:
         print(i, "is not present")

輸出:

resources.sh is present
server.properties is present
resources.csv is present
resources.log is present
sampleresources.csv is not present
actual = ['resources.sh', 'server.properties', 'resources.csv','resources.log', 'sampleresources.csv']
expected = ['resources.sh', 'server.properties', 'resources.csv',  'resources.log']
for i in actual:
    if i in expected:print "{} is present".format(i)
    else:print "{} is not present".format(i)

輸出:

resources.sh is present
server.properties is present
resources.csv is present
resources.log is present
sampleresources.csv is not present
[print ("{} is present".format(b)) if b in expected  
else print("{} is not present".format(b)) for b in actual]
actual = ['resources.sh', 'server.properties', 'resources.csv', 'resources.log', 'sampleresources.csv']
expected = ['resources.sh', 'server.properties', 'resources.csv', 'resources.log']

result = [elem + ' is present' if elem in expected else elem + ' is not present' for elem in actual]
print result

您可以使用列表理解來獲得更簡潔的代碼:

  actual = ['resources.sh', 'server.properties', 'resources.csv', 'resources.log', 'sampleresources.csv']
  expected = ['resources.sh', 'server.properties', 'resources.csv', 'resources.log']

  def print_msg(x):
      print(x,'is present')

  [print_msg(b) for i in actual for b in expected if i == b]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM