赞
踩
题目描述:
一组学生,每个学生有身高和体重两个特征,现在要对这些学生排序:先按照身高排序,身高相同的按照体重排序
1.用字典来存储 身高和体重的键值对,基于题目描述,身高存在相同的情况,所以体重作为键
不要因为先排序身高,第一次就排序身高,否则第二次排序会将已排序的序列打乱
dic = {80: 180, 70: 180, 60: 190, 90: 190, 56: 180}
ls1 = sorted(dic.items(), key=lambda kv: kv[0])
print(ls1)
ls2 = sorted(ls1, key=lambda kv: kv[1])
print(ls2)
输出为:
[(56, 180), (60, 190), (70, 180), (80, 180), (90, 190)]
[(56, 180), (70, 180), (80, 180), (60, 190), (90, 190)]
2.1存在问题:体重也存在相同的情况,作为键值就不合理,换列表存储,每个元素是(weight,height),先后顺序也可以调换
weight_height = [(66, 180), (66, 190), (70, 160), (70, 180), (60, 170), (80, 170)]
ls1 = sorted(weight_height, key=lambda kv: kv[0])
print(ls1)
ls2 = sorted(ls1, key=lambda kv: kv[1])
print(ls2)
输出为:
[(60, 170), (66, 180), (66, 190), (70, 160), (70, 180), (80, 170)]
[(70, 160), (60, 170), (80, 170), (66, 180), (70, 180), (66, 190)]
3.变更一下,先按照体重排序,体重相同的按照身高排序
直接修改排序的先后顺序即可
weight_height = [(66, 180), (66, 190), (70, 160), (70, 180), (60, 170), (80, 170)]
ls1 = sorted(weight_height, key=lambda kv: kv[1])
print(ls1)
ls2 = sorted(ls1, key=lambda kv: kv[0])
print(ls2)
输出为:
[(70, 160), (60, 170), (80, 170), (66, 180), (70, 180), (66, 190)]
[(60, 170), (66, 180), (66, 190), (70, 160), (70, 180), (80, 170)]
4.题目拓展,学生是有编号的,先按照身高排序,身高相同的按照体重排序,身高和体重相同的按照编号排序
所以,排序的先后顺序就是:编号 体重 身高
weight_height = [(0, 66, 180), (1, 66, 190), (2, 66, 190), (3, 70, 160), (4, 70, 160), (5, 70, 180), (6, 60, 170),
(7, 80, 170), (8, 70, 170)]
ls1 = sorted(weight_height, key=lambda kv: kv[0])
print(ls1)
ls2 = sorted(ls1, key=lambda kv: kv[1])
print(ls2)
ls3 = sorted(ls2, key=lambda kv: kv[2])
print(ls3)
输出为:
[(0, 66, 180), (1, 66, 190), (2, 66, 190), (3, 70, 160), (4, 70, 160), (5, 70, 180), (6, 60, 170), (7, 80, 170), (8, 70, 170)]
[(6, 60, 170), (0, 66, 180), (1, 66, 190), (2, 66, 190), (3, 70, 160), (4, 70, 160), (5, 70, 180), (8, 70, 170), (7, 80, 170)]
[(3, 70, 160), (4, 70, 160), (6, 60, 170), (8, 70, 170), (7, 80, 170), (0, 66, 180), (5, 70, 180), (1, 66, 190), (2, 66, 190)]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。