首页 > 解决方案 > cmp_to_key 在 python3 中不适用于 .csv 文件

问题描述

我正在处理.csv文件,所以我需要按特定列排序这个答案不起作用:

使用两个 key= 参数进行排序

因此使用来自的想法

如何在 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

标签: pythonpython-3.xsortingpyicu

解决方案


我认为您的呼叫使用错误的键功能排序。

来自docs.python.org

key 参数的值应该是一个函数,它接受一个参数并返回一个用于排序目的的键。这种技术很快,因为每个输入记录只调用一次键函数。

您的键 lambda 返回一个包含字符和函数的元组。

python3首先按第一项对元组进行排序,因此“Α”与“α”(字节顺序,不按字母顺序)进行比较,如果它们相等,则将 collat​​or.getSortKey 与 collat​​or.getSortKey 进行比较。

我认为您想使用以下 lambda,我相信它传达了您想要发生的事情。

foo = sorted(parts, key=lambda s: collator.getSortKey(s[1]))

这应该按字母顺序而不是字节顺序排序。


推荐阅读