Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中有没有办法找到名称中数字最小的文件?_Python_Python 3.x - Fatal编程技术网

Python中有没有办法找到名称中数字最小的文件?

Python中有没有办法找到名称中数字最小的文件?,python,python-3.x,Python,Python 3.x,我有一系列由一个脚本创建的文档,它们都被称为: name_*score* *score*是一个浮点数,我需要在另一个脚本中标识文件夹中编号最小的文件。例如: name_123.12 name_145.45 这应该返回字符串“name_123.12”作为键函数。您可以使用它来定义计算min的方式: files = [ "name_123.12", "name_145.45", "name_121.45", "name_121.457" ] min(files,

我有一系列由一个脚本创建的文档,它们都被称为:

name_*score*
*score*
是一个浮点数,我需要在另一个脚本中标识文件夹中编号最小的文件。例如:

name_123.12
name_145.45
这应该返回字符串“name_123.12”

作为键函数。您可以使用它来定义计算
min
的方式:

files = [
    "name_123.12",
    "name_145.45",
    "name_121.45",
    "name_121.457"
]

min(files, key=lambda x: float((x.split('_')[1])))

# name_121.45

您可以先尝试获取数字部分,然后将其转换为float和sort。 例如:

new_list = [float(name[5:]) for name in YOURLIST] # trim out the unrelated part and convert to float
result = 'name_' + str(min(new_list)) # this is your result

我只是想说Mark Meyer在这一点上是完全正确的,但您还提到您正在从目录中读取这些文件名。在这种情况下,您可以在Mark的答案中添加一些代码:

import glob, os
os.chdir("/path/to/directory")
files = glob.glob("*")

print(min(files, key=lambda x: float((x.split('_')[1]))))

通过提供目录获取最低值的一种方法

import os
import re
import sys

def get_lowest(directory):
    lowest = sys.maxint
    for filename in os.listdir(directory):
        match = re.match(r'name_\d+(?:\.\d+)', filename)
        if match:
            number = re.search(r'(?<=_)\d+(?:\.\d+)', match.group(0))
            if number:
                value = float(number.group(0))
                if value < lowest:
                    lowest = value
    return lowest

print(get_lowest('./'))
导入操作系统
进口稀土
导入系统
def get_最低(目录):
最低=sys.maxint
对于os.listdir(目录)中的文件名:
match=re.match(r'name\ud+(?:\。\d+),文件名)
如果匹配:

number=re.search(r’(?OP在从实际的文件目录中查找最小数量的文件时是否遇到问题(尽管方法相同)?@Austin我将文件列表更改为我所有文件的列表,并且成功了