在路径中找到每个目录名['spam', 'eggs']
的最佳pythonic方法是什么? "/home/user/spam/eggs"
用法示例(不起作用,但解释了我的情况):
dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
if path.find(dirs):
print "All dirs are present in the path"
由于
答案 0 :(得分:9)
set.issubset
>>> set(['spam', 'eggs']).issubset('/home/user/spam/eggs'.split('/'))
True
答案 1 :(得分:5)
看起来你想要的东西......:
if all(d in path.split('/') for d in dirs):
...
这种单行样式效率低下,因为它保持每个d的分割路径(并且分割产生一个列表,而一个集合更适合成员资格检查)。把它变成2线:
pathpieces = set(path.split('/'))
if all(d in pathpieces for d in dirs):
...
极大地提高了表现。
答案 2 :(得分:2)
names = ['spam', 'eggs']
dir = "/home/user/spam/eggs"
# Split into parts
parts = [ for part in dir.split('/') if part != '' ]
# Rejoin found paths
dirs = [ '/'.join(parts[0:n]) for (n, name) in enumerate(parts) if name in names ]
编辑:如果您只想验证所有目录是否存在:
parts = "/home/user/spam/eggs".split('/')
print all(dir in parts for dir in ['spam', 'eggs'])
答案 3 :(得分:1)
也许这就是你想要的?
dirs = ['spam', 'eggs']
path = "/home/user/spam/eggs"
present = [dir for dir in dirs if dir in path]
答案 4 :(得分:0)
使用生成器的一个班轮(使用文本查找而不是将名称视为与文件系统有关 - 您的请求对我来说并不完全清楚)
[x for x in dirs if x in path.split( os.sep )]