13

我正在尝试以人类可读的方式显示一些结果。出于这个问题的目的,其中一些是数字,一些是字母,一些是两者的组合。

我试图弄清楚如何让它们像这样排序:

input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
sorted_input = sorted(input)
print(sorted_input)

期望的结果:

['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello']

实际结果:

['0', '1', '10', '100', '2', '3', 'Allowance', 'Hello']

我很难想出如何做到这一点。

4

5 回答 5

14

1 - 安装 natsort 模块

pip install natsort

2 - 导入 natsorted

>>> input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']

>>> from natsort import natsorted
>>> natsorted(input)
['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello']

来源:https ://pypi.python.org/pypi/natsort

于 2013-10-27T23:24:51.293 回答
3

我发现以下链接中有关自然排序顺序的代码在过去非常有用:

http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html

于 2013-10-27T23:22:10.380 回答
1

这会做到的。出于比较的目的,它将可以转换为整数的字符串转换为该整数,并且不理会其他字符串:

def key(s):
    try:
        return int(s)
    except ValueError:
        return s

sorted_input = sorted(input, key=key)
于 2013-10-27T23:23:47.383 回答
0

对于您的具体情况:

def mySort(l):
    numbers = []
    words = []
    for e in l:
        try:
            numbers.append(int(e))
        except:
            words.append(e)
    return [str(i) for i in sorted(numbers)] + sorted(words)

print mySort(input)
于 2013-10-27T23:25:04.283 回答
0

您可以拆分列表,排序,然后将其重新组合在一起。尝试这样的事情:

numbers = sorted(int(i) for i in input_ if i.isdigit())
nonnums = sorted(i for i in input_ if not i.isdigit())
sorted_input = [str(i) for i in numbers] + nonnums

你必须做一些比isdigit你可以有非整数更复杂的事情。

如果这不涵盖您的“一些是两者的组合”,请详细说明这意味着什么以及您期望从它们那里得到什么输出。

(未经测试,但应该传达这个想法。)

于 2013-10-27T23:25:49.797 回答