如何检查列表项是否存在于另一个列表中

时间:2017-08-02 18:22:42

标签: python 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

5 个答案:

答案 0 :(得分:2)

您只需循环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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

[print ("{} is present".format(b)) if b in expected  
else print("{} is not present".format(b)) for b in actual]

答案 3 :(得分:0)

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

答案 4 :(得分:0)

您可以使用list comrehension来获得更清晰的代码:

  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]