Python 的 自定义比较器

等级 4191 次按键

这使用cmp_to_key把比较函数转换为排序键,按长度对单词排序。

Python 代码

# cmp_to_key把双参数比较函数转换成排序键
1from functools import cmp_to_key
2
# 比较函数:a在前返回负数,b在前返回正数,相等返回0
3def compare(a, b):
# 按长度比较:较短的字符串排在前面
4 return len(a) - len(b)
5
# 长度分别为5、2、6、3的单词
6words = ["apple", "hi", "banana", "cat"]
# sorted()只接受key=,所以用cmp_to_key包装compare
7sorted_words = sorted(words, key=cmp_to_key(compare))
# 打印['hi', 'cat', 'apple', 'banana']
8print(sorted_words)

运行结果

['hi', 'cat', 'apple', 'banana']
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • "× 8
  • _× 6
  • (× 6
  • )× 6
  • ,× 5
  • =× 3
  • -× 1
  • :× 1
  • [× 1
  • ]× 1

Python 等级 4 的更多代码示例

← 返回 Python 打字练习