Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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_Pandas - Fatal编程技术网

Python以数字形式列出文件

Python以数字形式列出文件,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一套文件 在每个文件中,都有一列对应于文件编号。它们都以这种格式命名: test_file_page_#_out_of_7000.txt 例如: test_file_page_1_out_of_7000.txt test_file_page_2_out_of_7000.txt test_file_page_7000_out_of_7000.txt 当我运行以下代码时: output_pages=os.listdir() 文件按以下顺序列出: 'test_file_Page_10_out_

我有一套文件

在每个文件中,都有一列对应于文件编号。它们都以这种格式命名:

test_file_page_#_out_of_7000.txt
例如:

test_file_page_1_out_of_7000.txt
test_file_page_2_out_of_7000.txt
test_file_page_7000_out_of_7000.txt
当我运行以下代码时: output_pages=os.listdir()

文件按以下顺序列出:

'test_file_Page_10_out_of_7000.txt', 'test_file_Page_11_out_of_7000.txt', ..., 'test_file_Page_1_out_of_7000.txt', 'test_file_Page_2_out_of_7000.txt'
'test_file_Page_1_out_of_7000.txt', 'test_file_Page_2_out_of_7000.txt', ..., 'test_file_Page_10_out_of_7000.txt', 'test_file_Page_11_out_of_7000.txt'
我希望文件按以下顺序列出:

'test_file_Page_10_out_of_7000.txt', 'test_file_Page_11_out_of_7000.txt', ..., 'test_file_Page_1_out_of_7000.txt', 'test_file_Page_2_out_of_7000.txt'
'test_file_Page_1_out_of_7000.txt', 'test_file_Page_2_out_of_7000.txt', ..., 'test_file_Page_10_out_of_7000.txt', 'test_file_Page_11_out_of_7000.txt'

有什么建议吗?

排序的
方法采用
参数,这是一个函数,它采用列表元素并返回应用于排序的值:

def get_number(filename):
    return int(filename.split("_")[3])
    
files = sorted(os.listdir(), key=get_number)

sorted
方法采用一个
key
参数,该参数是一个函数,它采用一个列表元素并返回应用于排序的值:

def get_number(filename):
    return int(filename.split("_")[3])
    
files = sorted(os.listdir(), key=get_number)

这很好用,我会在5分钟内接受它作为我的答案?为什么它不是key=get_number(os.listdir())或其他传递的内容?这个函数有一个参数,虽然它正在传递一个参数,但它似乎没有传递一个参数。这个问题很好。
sorted
函数接受您提供的
函数,并在对元素进行排序时在内部使用它。因此,调用该函数实际上不是我们的责任,它是经过排序的。这很好用,我会在5分钟内接受它作为答案。尽管如此,问题是,为什么key=get\u number有效?为什么它不是key=get_number(os.listdir())或其他传递的内容?这个函数有一个参数,虽然它正在传递一个参数,但它似乎没有传递一个参数。这个问题很好。
sorted
函数接受您提供的
函数,并在对元素进行排序时在内部使用它。因此,调用该函数实际上不是我们的责任,它是排序的。