按字典顺序排序结果?

时间:2013-10-27 23:16:18

标签: python sorting

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

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

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']

我无法想出如何做到这一点。

5 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:3)

我在以下链接中找到了关于自然排序顺序的代码,过去非常有用:

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

答案 2 :(得分:1)

这样做。为了进行比较,它将可以转换为整数的字符串转换为该整数,并保留其他字符串:

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

sorted_input = sorted(input, key=key)

答案 3 :(得分: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)

答案 4 :(得分: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更复杂的事情。

如果这不包括“某些是两者的组合”,请详细说明这意味着什么,以及您对它们的期望。

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

相关问题