python - 如何在 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:改变这种行为的原因是什么?
我知道将数字与字符串或其他对象进行比较通常是有问题的。然而,旧的行为对于实现尊重数值的字典排序很有用。
解决方案
推荐阅读
- excel - 返回一个范围内空白单元格的总和或计数,具有多个输入,但计数列可能不同
- excel - EXCEL - 检查列值并复制另一个
- wamp - 使用 WampServer 使我的网站上线(不是本地主机)
- python - 用python绘制交错等距图
- flutter - 带BottomAppBar 的快速拨号
- powershell - Powershell:如何从文本文件中不符合条件的行中删除 CRLF
- python - Raster - 在 rasterstack 中计算每个类别的像素并使用 python 写入数据帧
- python - MySQLdb._exceptions.ProgrammingError:格式字符串的参数不足
- powershell - 使用powershell根据键更新csv的多列
- c# - 获取checkedListbox中选中项的索引和名称