<jupyter_start><jupyter_text>键排序<jupyter_code># 首先创建一个元组组成的列表来测试排序

employee_records = [('Joe',1,54),('Roc',4,24),('Tom',2,19),('Lisy',3,20),('Shaly',6,21),('Jim',5,22)]
employee_records
# 使用名字进行排序
print sorted(employee_records,key=lambda emp:emp[0])
# ID排序
print sorted(employee_records,key=lambda emp:emp[1])
# 年龄排序
print sorted(employee_records,key=lambda emp:emp[2])<jupyter_output>[('Tom', 2, 19), ('Lisy', 3, 20), ('Shaly', 6, 21), ('Jim', 5, 22), ('Roc', 4, 24), ('Joe', 1, 54)]<jupyter_text>使用operator操作符<jupyter_code>from operator import itemgetter

employee_records = [('Joe',1,54),('Roc',4,24),('Tom',2,19),('Lisy',3,20),('Shaly',6,21),('Jim',5,22)]

print sorted(employee_records,key=itemgetter(1))<jupyter_output>[('Joe', 1, 54), ('Tom', 2, 19), ('Lisy', 3, 20), ('Roc', 4, 24), ('Jim', 5, 22), ('Shaly', 6, 21)]<jupyter_text>itemgetter 可以接受多个用来排序的域<jupyter_code>print sorted(employee_records,key=itemgetter(0,1))<jupyter_output>[('Jim', 5, 22), ('Joe', 1, 54), ('Lisy', 3, 20), ('Roc', 4, 24), ('Shaly', 6, 21), ('Tom', 2, 19)]<jupyter_text>如果可迭代对象里的元素是类对象，则可以用attrgetter和methodcaller<jupyter_code># 将雇员记录封装成类

class employee():
    
    def __init__(self,name,id,age):
        self.name = name
        self.id = id
        self.age = age
        
    def attr_print(self):
        print self.name,self.id,self.age
        
        
employee_records = []
emp1 = employee('koe',1,25)
emp2 = employee('roc',3,24)
emp3 = employee('jim',2,24)

employee_records.append(emp1)
employee_records.append(emp2)
employee_records.append(emp3)

# print
for emp in employee_records:
    emp.attr_print()
from operator import attrgetter

employee_records_sorted = sorted(employee_records,key=attrgetter('age'))

for emp in employee_records_sorted:
    print emp.attr_print()<jupyter_output>3
roc 3 24
None
jim 2 24
None
koe 1 25
None
{'fraction_non_alphanumeric': 0.1949754232659749, 'fraction_numerical': 0.06608410704533042, 'mean_word_length': 6.4471544715447155, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '257569', 'license': 'Apache-2.0', 'n_tokens_mistral': 890, 'n_tokens_neox': 799, 'n_words': 132, 'path': '008key_sort.ipynb', 'repo_name': 'Roc-J/Python_data_science', 'size': '1831'}