Python 对结果进行非词典排序?
我试图以人类可读的方式显示一些结果。就这个问题而言,有些是数字,有些是字母,有些是两者的组合 我正在想办法让他们这样分类:Python 对结果进行非词典排序?,python,sorting,Python,Sorting,我试图以人类可读的方式显示一些结果。就这个问题而言,有些是数字,有些是字母,有些是两者的组合 我正在想办法让他们这样分类: input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance'] sorted_input = sorted(input) print(sorted_input) numbers = sorted(int(i) for i in input_ if i.isdigit()) nonnums = sorted(i
input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
sorted_input = sorted(input)
print(sorted_input)
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
预期结果:
['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello']
实际结果:
['0', '1', '10', '100', '2', '3', 'Allowance', 'Hello']
我想不出如何做到这一点。我发现以下链接中关于自然排序顺序的代码在过去非常有用:
这样就可以了。出于比较目的,它将可转换为整数的字符串转换为该整数,并保留其他字符串:
def key(s):
try:
return int(s)
except ValueError:
return s
sorted_input = sorted(input, key=key)
1-安装natsort模块
pip install natsort
2-导入已排序的文件
>>> input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
>>> from natsort import natsorted
>>> natsorted(input)
['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello']
来源:针对您的具体情况:
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)
您可以将列表拆分、排序,然后重新组合。试着这样做:
input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
sorted_input = sorted(input)
print(sorted_input)
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更复杂的操作
如果这还不包括您的“一些是两者的结合”,请详细说明这意味着什么,以及您期望从中获得什么样的输出
(未经测试,但应传达该想法。)可能重复我认为您遗漏了这一部分“有些是两者的结合。”。在Python3中也不起作用,因为“无序类型”不,我看到了,但忽略了它,因为在这种情况下,他们一句话也没说想要什么;-)“面对模棱两可的局面,拒绝猜测的诱惑。”我本应该更清楚:)太棒了——这正是我所需要的!我很高兴看到
natsort
对我以外的人有用。谢谢你的推荐!感谢您编写natsort
模块@SethMMorton。它真的很方便。这对理解它是如何工作的非常有用,我在标记这个和明宇的之间左右为难,我最终选择了明宇的,因为它实际上有一个可用的解决方案,但这是一本很棒的书。