python - cmp_to_key 在 python3 中不适用于 .csv 文件
问题描述
我正在处理.csv
文件,所以我需要按特定列排序这个答案不起作用:
因此使用来自的想法
如何在 Python 中按字母顺序对 unicode 字符串进行排序?
我们有
在python2
import icu # conda install -c conda-forge pyicu
collator = icu.Collator.createInstance(icu.Locale('el_GR.UTF-8'))
parts = [('3', 'ά', 'C'),
('6', 'γ', 'F'),
('5', 'β', 'E'),
('4', 'Ἀ', 'D'),
('2', 'Α', 'B'),
('1', 'α', 'A')]
foo = sorted(parts, key=lambda s: (s[1]), cmp=collator.compare)
for c in foo:
print c[0], c[1].decode('utf-8'), c[2]
结果正确:
1 α A
2 Α B
4 Ἀ D
3 ά C
5 β E
6 γ F
但在python3
import icu # conda install -c conda-forge pyicu
from functools import cmp_to_key
collator = icu.Collator.createInstance(icu.Locale('el_GR.UTF-8'))
parts = [('3', 'ά', 'C'),
('6', 'γ', 'F'),
('5', 'β', 'E'),
('4', 'Ἀ', 'D'),
('2', 'Α', 'B'),
('1', 'α', 'A')]
foo = sorted(parts, key=lambda s: (s[1], collator.getSortKey))
#foo = sorted(parts, key=lambda s: (s[1], collator.compare))#the same result as collator.getSortKey
for c in foo:
print (c[0], c[1], c[2])
结果错误:
2 Α B
1 α A
5 β E
6 γ F
4 Ἀ D
3 ά C
解决方案
我认为您的呼叫使用错误的键功能排序。
key 参数的值应该是一个函数,它接受一个参数并返回一个用于排序目的的键。这种技术很快,因为每个输入记录只调用一次键函数。
您的键 lambda 返回一个包含字符和函数的元组。
python3首先按第一项对元组进行排序,因此“Α”与“α”(字节顺序,不按字母顺序)进行比较,如果它们相等,则将 collator.getSortKey 与 collator.getSortKey 进行比较。
我认为您想使用以下 lambda,我相信它传达了您想要发生的事情。
foo = sorted(parts, key=lambda s: collator.getSortKey(s[1]))
这应该按字母顺序而不是字节顺序排序。
推荐阅读
- unity3d - 新的输入系统不发送消息?
- css - 如何使用引导程序制作响应式表格
- mysql - MYSQL 如何制作下拉列表?
- angular - 如何在角度中使用点击和地图
- vuetify.js - 多个 Vuetify 数据表导致糟糕的性能?
- java - 如何在 Java 中表示和操作大于 24:00 的时间值?
- python - 无法连接到 Docker 容器中的 PostgreSQL 数据库
- php - Bootstrap 下拉 - 当 URL 中的 id 时不下拉
- r - 为什么 colnames 函数与管道运算符和 [ 选择器一起使用时会生成 tibble(而不是向量)?
- python - InvalidArgumentError:预期 'tf.Tensor(False, shape=(), dtype=bool)' 为真