sorted
和sort()
li = [9, 1, 8, 2, 7, 3, 6, 4, 5]
s_li = sorted(li)
print ('Sorted Variable: ', s_li)
li.sort()
print ('Original Variable: ', li)
输出结果:
Sorted Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Original Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]
如果:
li = [9, 1, 8, 2, 7, 3, 6, 4, 5]
s_li = li.sort()
print(s_li)
输出的结果是:
None
Tuple不能使用sort()
,只能定义一个新的变量=sorted(a_tuple)
。
class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def __repr__(self):
return '({},{},${})'.format(self.name, self.age, self.salary)
e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)
employees = [e1, e2, e3]
def e_sort(emp):
return emp.name
s_employees = sorted(employees, key=e_sort)
print(s_employees)
或者利用lambda
函数:
s_employees = sorted(employees, key=lambda e: e.name)
或者使用operator
模块中的attrgetter
:
s_employees = sorted(employees, key=attrgetter('age'))