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

2024-09-27 07:27:07 发布

您现在位置: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

我真的只是想让它说,文件没有找到一次明显的,如果它没有找到。只是有点不懂逻辑。顺便说一句,我不想使用检查精确匹配是,这就是为什么我使用'在'如果条件时,遍历


Tags: inselftxthelloforthatloggerthis
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:07

将两个列表都转换为set并使用minus将是更好的解决方案

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')

相关问题 更多 >

    热门问题