当前位置:   article > 正文

python实现-身高和体重排序_python 按照身高体重排序

python 按照身高体重排序

题目描述:
一组学生,每个学生有身高和体重两个特征,现在要对这些学生排序:先按照身高排序,身高相同的按照体重排序

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出为:

[(56, 180), (60, 190), (70, 180), (80, 180), (90, 190)]
[(56, 180), (70, 180), (80, 180), (60, 190), (90, 190)]
  • 1
  • 2

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出为:

[(60, 170), (66, 180), (66, 190), (70, 160), (70, 180), (80, 170)]
[(70, 160), (60, 170), (80, 170), (66, 180), (70, 180), (66, 190)]
  • 1
  • 2

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)
  • 1
  • 2
  • 3
  • 4
  • 5

输出为:

[(70, 160), (60, 170), (80, 170), (66, 180), (70, 180), (66, 190)]
[(60, 170), (66, 180), (66, 190), (70, 160), (70, 180), (80, 170)]

  • 1
  • 2
  • 3

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

输出为:

[(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)]
  • 1
  • 2
  • 3
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/442143?site
推荐阅读
相关标签
  

闽ICP备14008679号