Python列表文件夹按数字顺序列出

我正在使用以下代码获取特定目录中所有文件夹的列表:

TWITTER_FOLDER = os.path.join('TwitterPhotos')
dirs = [d for d in os.listdir(TWITTER_FOLDER) if os.path.isdir(os.path.join(TWITTER_FOLDER,d))]

这是数组:['1','2','3','4','5','6','7','8','9','10','11']

我想按以下顺序获取数组:['11','1']

因此,我将以下代码用于此目的:

dirs.sort(key=lambda f: int(filter(str.isdigit,f)))

当我使用它时,出现此错误:

int() argument must be a string,a bytes-like object or a number,not 'filter'

任何主意是什么问题?或如何以其他方式对其进行排序? 重要的是,数组将按数字顺序排序,例如:

12 11 10 9 8 7 6 5 4 3 2 1

不是:

9 8 7 6 5 4 3 2 12 11 1

谢谢!

zkx993299184 回答:Python列表文件夹按数字顺序列出

Filter返回一个迭代器,您需要将它们重新连接为字符串,然后才能将其转换为整数

dirs.sort(key=lambda f: int(''.join(filter(str.isdigit,f))))
,

使用sorted和密钥:

In [4]: sorted(f,key=lambda x: int(x),reverse=True)
Out[4]: ['11','10','9','8','7','6','5','4','3','2','1']

或者您可以进行f.sort(key=lambda x:int(x),reverse=True)进行就地排序。

本文链接:https://www.f2er.com/3146480.html

大家都在问