如何查找列表元素是否包含在其他列表中而没有完全匹配

时间:2019-01-18 02:51:34

标签: python

baseNames = ["this","that","howdy","hello","anotherfile"]
testList = ["this.txt","that.txt","howdy.txt","hello.txt"]

def _validateFilesExist(self):
    for basename in self.baseNames:
        self.baseNameCounter+=1
        self.logger.logInfo("Looking for file-> " + basename)
        for filename in self.testList:
                if basename  in filename:
                    self.counter+=1
                    self.logger.logInfo("File was found")
                #else:          
                #   self.logger.logInfo(basename)                   
    if self.counter != self.baseNameCounter:
        raise Exception("All files not avaialble")
    else:
        self.logger.logInfo("All files available")

输出: I like this output but Im trying to figure out how to get the last file that was not found to display "file not found"

如果我取消注释底部的else语句,这就是输出的样子……

enter image description here

我真的只是想让它说一次找不到文件,如果找不到的话。逻辑上只停留了一点。附言我不想使用检查是否完全匹配,这就是为什么在遍历时使用“ in”条件的原因。

1 个答案:

答案 0 :(得分:0)

将两个列表都转换为设置并使用减号将是一个更好的解决方案

diff_files = list(set(baseNames) - set(testList))

为您的最终目的检查len(diff_files)

更新1:

下面的代码是个主意,它可能不是最佳的。

baseNames = ["this", "that", "howdy", "hello", "anotherfile"]
testList = ["this.txt","that.txt","howdy.txt","hello.txt"]
existed_files = list()
for basename in baseNames:
    for filename in testList:
        if basename in filename:
            existed_files.append(basename)
            break

if (len(existed_files) != len(baseNames)):
    raise Exception('Not all matched')

更新2:仅获取不存在的文件

baseNames = ["this", "that", "howdy", "hello", "anotherfile"]
testList = ["this.txt","that.txt","howdy.txt","hello.txt"]
not_found_files = set()
for basename in baseNames:
    found = False
    for filename in testList:
        if basename in filename:
            found = True
            break
    if not found:
        not_found_files.add(basename)

if not_found_files:
    print('Not found files')
    print(not_found_files)
    raise Exception('Not all matched')