繁体   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