假设有一个包含名字和书名信息的列表name_list和字典book_dict,其中book_dict的键为书名,值为作者名字。可以使用lambda函数和sorted函数进行排序,代码如下:
name_list = [('Amy Lee', 'The Open Door'), ('John Smith', 'The Catcher in the Rye'),
('Jane Doe', 'The Catcher in the Rye'), ('Tom Carter', 'The Lord of the Rings')]
book_dict = {'The Open Door': 'Amy Lee', 'The Catcher in the Rye': 'J.D. Salinger',
'The Lord of the Rings': 'J.R.R. Tolkien'}
sorted_list = sorted(name_list, key=lambda x: (x[0].split()[1], book_dict[x[1]] if x[1] in book_dict else x[1]))
print(sorted_list)
输出结果为:
[('Jane Doe', 'The Catcher in the Rye'), ('John Smith', 'The Catcher in the Rye'),
('Amy Lee', 'The Open Door'), ('Tom Carter', 'The Lord of the Rings')]
通过lambda函数的key参数,先按照名字的姓氏排序,再按照书名排序。如果名字相同而书名不存在于book_dict中,则按照原书名排序。最后将排序后的列表存入sorted_list中。