【问题标题】:How to fetch directory with highest number in python如何在python中获取最高编号的目录
【发布时间】:2022-01-01 18:04:30
【问题描述】:

如何选择数量最多的目录

例如。

  1. a/b/c/d.1/log/
  2. a/b/c/d/logs/
  3. a/b/c/d.3/logs/
  4. a/b/c/d.2/logs/

现在我只想选择 a/b/c/d.3/logs 下生成的目录下的那些日志,因为 d.3​​ 是最好的

结果或打印 = "a/b/c/d.3/logs/"

【问题讨论】:

  • 数字总是排在第四位吗?输入是什么(列表、字符串、其他)?

标签: python python-3.x directory


【解决方案1】:

假设输入是一个字符串列表,并且您想匹配第四级目录,您可以使用正则表达式提取数字并使用max 获取最大值:

dirs = ['a/b/c/d.1/log/',
        'a/b/c/d/logs/',
        'a/b/c/d.3/logs/',
        'a/b/c/d.2/logs/',
        'a/b/c/d.11/logs/',
       ]

def get_int(s, pos=3):
    m = re.search(r'(?:.+?/){3}[^/\d]+(\d+)/', s)
    return int(m.group(1)) if m else -1

max(dirs, key=get_int)

输出:

'a/b/c/d.11/logs/'

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    相关资源
    最近更新 更多