假设我有以下Python列表:
mylist = [
["name_a", "sex_male", "age_15", "grade_11"],
["name_b", "sex_male", "age_18", "grade_9"],
["name_c", "sex_male", "age_11", "grade_8"],
["name_d", "sex_male", "age_16", "grade_12"],
["name_e", "sex_male", "age_19", "grade_13"],
]
我想调用Python的sort()函数,按年龄
对 mylist 进行排序例如,我想做这样的事情:
mylist.sort(key=...)
获取输出
mylist = [
["name_c", "sex_male", "age_11", "grade_8"],
["name_a", "sex_male", "age_15", "grade_11"],
["name_d", "sex_male", "age_16", "grade_12"],
["name_b", "sex_male", "age_18", "grade_9"],
["name_e", "sex_male", "age_19", "grade_13"],
]
这样做的正确方法是什么?
P.S
还有一个问题:为什么在Python的sort()函数中使用排序算法? (例如QuickSort?)
答案 0 :(得分:2)
def extract_age(item):
"""age is stored in the 3rd element of item. eg.
['name_c', 'sex_male', 'age_11', 'grade_8']
and should be returned as an int
"""
return int(item[2].split('_')[1])
mylist.sort(key=extract_age)
答案 1 :(得分:1)
假设所有年龄段看起来都一样:
>>>mylist.sort(key=lambda e: int(e[2].split('_')[1]))
[['name_c', 'sex_male', 'age_11', 'grade_8'],
['name_a', 'sex_male', 'age_15', 'grade_11'],
['name_d', 'sex_male', 'age_16', 'grade_12'],
['name_b', 'sex_male', 'age_18', 'grade_9'],
['name_e', 'sex_male', 'age_19', 'grade_13']]
lambda
表达式解析年龄字段,方法是在_
字符上拆分字符串,然后转换为int
拆分第二个元素的结果。
Python使用TimSort
算法,这是由Tim Peters创建的Python定制搜索算法。