Python进阶教程4-3,用Python3怎么写
教程都是根据2.7写的,用的cmp,虽然也没看懂,求解释,重点是3版本怎么写,sorted要用key表达,求大神解疑
教程都是根据2.7写的,用的cmp,虽然也没看懂,求解释,重点是3版本怎么写,sorted要用key表达,求大神解疑
2018-04-23
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- from functools import cmp_to_key class Person: pass p1 = Person() p1.name = 'Bart' p2 = Person() p2.name = 'Adam' p3 = Person() p3.name = 'Lisa' L1 = [p1, p2, p3] def mycmp(p1, p2): if p1.name > p2.name: return 1 elif p1.name < p2.name: return -1 else: return 0 L2 = sorted(L1, key=cmp_to_key(mycmp)) print(L2[0].name) print(L2[1].name) print(L2[2].name)
举报