簡體   English   中英

不同字符數的文件名排序列表

[英]Sort List of File Names with Different Amount of Characters

我遇到了一個問題,我需要格式為 xxx_00000、xxx_00001 的文件的排序列表。 問題是當文件超過 100000 個時,格式變為 xxx_100000,而所有其他文件保持不變。 這意味着當我執行 os.listdir(directory) 時,我會在 xxx_100000 旁邊得到 xxx_10000(即 xxx_10000 是索引 10,000,xxx_100000 是索引 10,001)。 關於如何排序以使它們以正確的順序顯示的任何想法? 我試過了:

sorted(paths)

sorted(paths, key=lambda x: x[x.rfind('_')+1:-4])

def sorted_helper(x):
    x = str(00000) + x[x.rfind('_')+1:-4]
    return x[-7:]

sorted(paths, key=sorted_helper)

您可能希望將其排序為 int,而不是字符串。 嘗試:

sorted(paths, key=lambda filename: int(filename.split("_")[1]))

您可以使用natsort.natsorted

from natsort import natsorted

natsorted(paths)

natsort庫在這種情況下會很有幫助。

例如:

from natsort import natsorted

natsorted(paths)

輸出:

['xxx_00001',
 'xxx_00002',
 'xxx_00100',
 'xxx_01000',
 'xxx_10000',
 'xxx_100001',
 'xxx_100010',
 'xxx_110000']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM