【问题标题】:MacOS Finder sorts alphabetically differently than Python .sort() [duplicate]MacOS Finder 按字母顺序排序不同于 Python .sort() [重复]
【发布时间】:2020-06-11 21:25:52
【问题描述】:

我有三个文件:

x10.txt
x30.txt
x200.txt

如果我转到我的 MacOS 查找器并按名称排序,我会得到以下顺序:

x10.txt
x30.txt
x200.txt

我试图在 Python 中以相同的顺序获取它们。我正在使用以下代码:

mypath = '/path/to/files/'
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
files.sort()

但是得到这个命令:

x10.txt
x200.txt
x30.txt

在 Python 中有没有一种方法可以按照它们在 Finder 中出现的顺序对这些文件进行排序?我想知道字母顺序是否有多种不同的约定。

【问题讨论】:

标签: python finder alphabetical-sort


【解决方案1】:

这看起来像natural sort order。数字按数值排序,与字符串的其余部分分开。

如果您正在寻找图书馆,可以使用natsort

>>> import natsort
>>> l = ['x10.txt', 'x30.txt', 'x200.txt']
>>> natsort.natsorted(l)
['x10.txt', 'x30.txt', 'x200.txt']

【讨论】:

  • 更好的方法是使用``` import os from natsort import os_sorted print(os_sorted(l)) ``
猜你喜欢
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 2017-12-19
  • 1970-01-01
相关资源
最近更新 更多