首页 > 解决方案 > 如何在 python3.x 中对混合类型的序列(例如数字和字符串)进行排序?

问题描述

当从 python2 迁移到 python3 时,我注意到无法再在 python3 中对混合类型的序列进行排序。

# Python2.7:
sorted(['foo', 'bar', 10, 200, 3])     
# => [3, 10, 200, 'bar', 'foo']

# Python3.6
sorted(['foo', 'bar', 10, 200, 3])
# => TypeError: '<' not supported between instances of 'str' and 'int'

问题 1。有没有办法切换回旧的行为?这对我的需求非常有用。特别是,以下内容对我不起作用,因为数字顺序错误:

# Python2/3
sorted(map(str,['foo', 'bar', 10, 200, 3]))
# => ['10', '200', '3', 'bar', 'foo']

这是语言规范的巨大变化,可能会破坏很多东西。问题 2:改变这种行为的原因是什么?

我知道将数字与字符串或其他对象进行比较通常是有问题的。然而,旧的行为对于实现尊重数值的字典排序很有用。

标签: pythonpython-3.xsorting

解决方案


推荐阅读