Pythonic 自定义排序字母等级 'D' 、 'C-' 、...、 'A+' ?

标签 python string sorting idioms

有没有比这更Pythonic、紧凑、直观的方式来对字母等级进行排序(不使用自定义字典)?

grades = ['B-','C','B','C+','A','D+','B+','C-','A+','D','A-']

sorted(grades, key=lambda g: (g[0], '+ -'.index((g+' ')[1])) )

['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D']

为了获得“X-”、“X”、“X+”的比较数字顺序,我添加了一个空格“”,以便 g[1] 始终存在,这样我就可以使用 .index() 来获取修饰符 '+ -' 的排名。

(动机 this question )

最佳答案

没有。

modmap = {
  '-': 0,
  '': 1,
  '+': 2
}

print(sorted(grades, key=lambda x: (-ord(x[0]), modmap[x[1:]])))

关于Pythonic 自定义排序字母等级 'D' 、 'C-' 、...、 'A+' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50111642/

相关文章:

python - 将 Python 与 YAML 结合使用

python - 皮查姆 : Failed to Create Interpreter Error occurred: Permission Denied - Windows 10

c++ - 在二叉搜索树中初始化字符串数组

PostgreSQL - 按 UUID 版本 1 时间戳排序

C# List<T> 使用 IComparer 参数排序给出编译错误

python多处理特有的内存管理

python - 如何在 Tweepy 中检查推文中的图像使用

c - memcpy 到宏中定义的字符串缓冲区

string - Lua:删除最后一个{..}

java - 如何从Map中获取最近100条数据?