[英]Pattern Matching between two lists - Python
i have a bunch of zip files in a directory and would like to get notified if one of them is missing . 我在目录中有一堆zip文件,如果其中一个缺少,我想得到通知。
Example code: 示例代码:
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)
Output: b = ['test-pattern1.zip', 'test-pattern2.zip', 'test-pattern3.zip'] 输出:b = ['test-pattern1.zip','test-pattern2.zip','test-pattern3.zip']
would like to match the contents of 'b' with 'a' and check if any of the zip files are missing 想要将'b'的内容与'a'匹配,并检查是否缺少任何zip文件
I would take a different approach: 我会采取另一种方法:
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)
You can convert the lists to sets and take their difference 1 : 您可以将列表转换为集合并采用它们的区别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)
Outputs: ['pattern3.zip']
输出:
['pattern3.zip']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.