functools.cmp_to_key(func)
2016-04-13 16:23
246 查看
将老式的比较函数(comparison function)转化为关键字函数(key function)。与接受key function的工具一同使用(如 sorted(), min(), max(), heapq.nlargest(), itertools.groupby())。该函数主要用来将程序转成 Python 3 格式的,因为 Python 3 中不支持比较函数。
比较函数是可调用的,接受两个参数,比较这两个参数并根据他们的大小关系返回负值、零或正值中的某一个。关键字函数也是可调用的,接受一个参数,同时返回一个可以用作排序关键字的值。
例如:
输出:
['-1', '-2', '3', '4', '9', '2', '3', '4', '5']
9, 5, 4, 4, 3, 3, 2, -1, -2
['1', '2', '3', '4', '5', '9']
9, 5, 4, 3, 2, 1
比较函数是可调用的,接受两个参数,比较这两个参数并根据他们的大小关系返回负值、零或正值中的某一个。关键字函数也是可调用的,接受一个参数,同时返回一个可以用作排序关键字的值。
例如:
sorted(iterable, key=cmp_to_key(locale.strcoll))
class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): from functools import cmp_to_key key = cmp_to_key(lambda x,y: int(y) - int(x)) res = ', '.join(sorted(map(str, nums), key=key)) return res or '0' nums = [-1,-2,3,4,9,2,3,4,5] s = Solution() print map(str, nums) #列表不去重 print s.largestNumber(nums) nums = {1,02,3,4,9,2,3,4,5} print map(str, nums) #字典会去重 print s.largestNumber(nums)
输出:
['-1', '-2', '3', '4', '9', '2', '3', '4', '5']
9, 5, 4, 4, 3, 3, 2, -1, -2
['1', '2', '3', '4', '5', '9']
9, 5, 4, 3, 2, 1
相关文章推荐
- lightoj 1294 - Positive Negative Sign 简单数学
- 制作OpenStack Windows Server 2012镜像
- Sybase 基础SQL查询
- 笔记(4/13)spring注解
- eval 为什么加括号
- C#索引器
- BroadcastReceiver广播接受者
- bzoj 3307: 雨天的尾巴
- 递归-汉诺塔问题
- Oracle正则表达式替换字符串
- Android Studio compile project添加一个本地项目依赖包时,提示程序包不存在
- WINCE下隐藏鼠标
- Objective-c与javascript交互[详细解读2]
- UVa 800提記錄
- Unity 与 Android融合
- 开发中 常用 js 记录
- SQLite语句
- 用自然语言的角度理解JavaScript中的this关键字
- Item 04:确定对象被使用前已先被初始化
- Linux下Shell编程实现基于Hadoop的ETL(流程篇)