检查哪些文件 [dict] 与给定路径匹配

Check which files [dict] match with given path

我有一个包含文件的字典:

files = {
    "/test/path/file1.c": "NotImportant",
    "/test/path/file2.c": "NotImportant",
    "/other/path/filex.c": "NotImportant",
    "/different/path/filez.c": "NotImportant"
    }

我现在有一个字典,例如path = '/test/path/' 并且我想查看这个特定路径中有哪个文件。 我试过

if path in files:
    print("found")

但是这对我不起作用。我通过遍历每个文件并使用相同语句检查的循环解决了这个问题。还有其他方法可以解决吗?

我的解决方案:

for file in files:
    if path in file:
        print("found")

为什么声明在这里有效而不是以前?我想要一个更好的解决方案,而不是遍历整个文件。

正如 DeepSpace 所说:none 你的元素是字典。

您的第一个元素确实是一个集合,第二个元素只是一个字符串,而 Python 字典是与值关联的键列表(就像一个词与真实字典中的定义关联)。

其次,要走的路是最好的做法:您必须查看文件中每个文件的路径名,以检查每个文件中是否存在 path = '/test/path/'这些文件。

就像人类一样!

这就是做这件事的好方法!

你可以使用正则表达式来匹配路径。

例如:

path_pattern = "^{}/.*".format(path)
for file in files:
    if re.match(path_pattern, file):
        print("Found")