簡體   English   中英

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

[英]how to find if list elements are contained in other list without exact match

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

輸出: 我喜歡這個輸出,但我想弄清楚如何讓最后一個找不到的文件顯示“找不到文件”

如果我取消注釋底部的 else 語句,這就是輸出的樣子......

在此處輸入圖片說明

我真的只是想讓它說如果沒有找到文件就很明顯地找不到文件。 只是有點卡在邏輯上。 PS我不想使用檢查精確匹配是,這就是為什么我在遍歷時使用'in'if條件。

將兩個列表都轉換為 set 並使用減號將是更好的解決方案

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

暫無
暫無

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

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