相关疑难解决方法(0)

Python是否具有用于字符串自然排序的内置函数?

使用Python 3.x,我有一个字符串列表,我想对其执行自然的字母排序.

自然排序: Windows中文件的排序顺序.

例如,以下列表是自然排序的(我想要的):

['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
Run Code Online (Sandbox Code Playgroud)

这是上面列表的"排序"版本(我有):

['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个行为与第一个类似的排序函数.

python sorting python-3.x

249
推荐指数
9
解决办法
8万
查看次数

PHP的natsort函数的Python模拟(使用"自然顺序"算法对列表进行排序)

我想知道Python中是否有类似PHP natsort函数的东西?

l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
l.sort()
Run Code Online (Sandbox Code Playgroud)

得到:

['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']
Run Code Online (Sandbox Code Playgroud)

但我想得到:

['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
Run Code Online (Sandbox Code Playgroud)

UPDATE

解决方案基于此链接

def try_int(s):
    "Convert to integer if possible."
    try: return int(s)
    except: return s

def natsort_key(s):
    "Used internally to get a tuple by which s is sorted."
    import re
    return map(try_int, re.findall(r'(\d+|\D+)', s))

def natcmp(a, b):
    "Natural string comparison, case sensitive."
    return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):
    "Natural string comparison, ignores case."
    return natcmp(a.lower(), b.lower())

l.sort(natcasecmp);
Run Code Online (Sandbox Code Playgroud)

python sorting natsort

22
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×2

sorting ×2

natsort ×1

python-3.x ×1