[英]Pattern Matching between two lists - Python
我在目錄中有一堆zip文件,如果其中一個缺少,我想得到通知。
示例代碼:
a = ['pattern1.zip', 'pattern2.zip', 'pattern3.zip']
b = []
for root,dirs,files in os.walk(some_path):
for i in files:
if i.endswith(('pattern1.zip', 'pattern2.zip', 'pattern3.zip')):
b.append(i)
輸出:b = ['test-pattern1.zip','test-pattern2.zip','test-pattern3.zip']
想要將'b'的內容與'a'匹配,並檢查是否缺少任何zip文件
我會采取另一種方法:
patterns = {'pattern1.zip', 'pattern2.zip', 'pattern3.zip'}
for root, dirs, files in os.walk(some_path):
for f in files:
for pattern in patterns:
if f.endswith(pattern):
patterns.remove(pattern)
break
print('Missing patterns:', patterns)
您可以將列表轉換為集合並采用它們的區別1 :
files_that_should_be_present = ['pattern1.zip', 'pattern2.zip', 'pattern3.zip']
files_that_are_present = ['pattern1.zip', 'pattern2.zip']
files_missing = list(set(files_that_should_be_present) - set(files_that_are_present))
print(files_missing)
輸出: ['pattern3.zip']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.