python-检查列表项是否包含在字符串中

python-检查列表项是否包含在字符串中,python,list,any,Python,List,Any,我有一个脚本,在这个脚本中,我正在遍历一个传递(通过csv文件)路径的列表。我想知道如何确定我当前使用的路径以前是否被管理过(作为父目录的子目录) 我保存了一个管理路径列表,如下所示: pathsManaged = ['/a/b', '/c/d', '/e'] 因此,当/如果下一个路径是'/e/a',我想在列表中检查路径管理的列表中是否存在此路径的父级 我迄今为止的努力: if any(currPath in x for x in pathsManaged): print 'subdir

我有一个脚本,在这个脚本中,我正在遍历一个传递(通过csv文件)路径的列表。我想知道如何确定我当前使用的路径以前是否被管理过(作为父目录的子目录)

我保存了一个管理路径列表,如下所示:

pathsManaged = ['/a/b', '/c/d', '/e']
因此,当/如果下一个路径是
'/e/a'
,我想在列表中检查
路径管理的
列表中是否存在此路径的父级

我迄今为止的努力:

if any(currPath in x for x in pathsManaged):
   print 'subdir of already managed path'
但这似乎不起作用。我对任何命令都期望过高。是否有其他快捷方式可用于此类型的查找


谢谢

如果我理解正确,您希望检查
路径管理
中是否有任何路径是
currPath
的一部分,但您的做法是相反的。 根据您的需要,其中一项应该适合您:

any(x in currPath for x in pathsManaged)

any(currPath.startswith(x) for x in pathsManaged)

os.path.dirname(currPath) in pathsManaged
也许:

from os.path import dirname

def parents(p):
    while len(p) > 1:
        p = dirname(p)
        yield p

pathsManaged = ['/a/b', '/c/d', '/e']

currPath = '/e/a'

if any(p in pathsManaged for p in parents(currPath)):
    print 'subdir of already managed path'
印刷品:

subdir of already managed path

假设pathsManaged包含绝对路径(否则我认为所有赌注都是无效的),那么可以将currPath设置为绝对路径,并查看它是否以pathsManaged中的任何路径开始。或者在Python中:

def is_path_already_managed(currPath):
    return any(
        os.path.abspath(currPath).startswith(managed_path)
        for managed_path in pathsManaged)

从概念上讲,我觉得pathsManaged应该是一个
集合
,而不是
列表

什么是currPath?您能给出一些示例和预期结果吗?如果
currPath
'/e/a'
,那么如果列表中有
'/'/code>或
'/a'
,则返回
True
。如果只考虑路径的开头,
any(路径管理中x的currPath.startswith(x))可能更好,或者pathsManaged中的os.path.dirname(currPath)
,但我不确定OP到底需要什么。谢谢。由于我对python比较陌生,我很想知道为什么在这种情况下,集合比列表更受欢迎。列表也可以正常工作,但它不应该包含两次相同的路径,顺序并不重要,唯一真正重要的是“这个路径是否在PathsManager中”,最接近这个概念的是集合。谢谢RemcoGerlich,我下次会用这个建议。