ToB企服应用市场:ToB评测及商务社交产业平台

标题: Python如何根据两个字段进行排序? [打印本页]

作者: 锦通    时间: 2022-10-24 09:47
标题: Python如何根据两个字段进行排序?
Python如何根据两个字段进行排序?
写这个博客,就是为了吐槽Python!
对于这个问题,首先,我花了一天时间,没有解决!
当然是百度了,一搜,有很多博客,无一例外,都是垃圾!
有的,只排数组!实体类不考虑了?
有的,只排数字!不排中文?Python中文排序有问题知不知道?!
有的,只排中文!就排了一个字段?
通过百度,倒时很快写出来一个,因为始终不对,折腾一天!
  1. # -*- coding: utf-8 -*-
  2. from itertools import chain
  3. from pypinyin import pinyin, Style
  4. class Student:
  5.     def __init__(self, name, age, height):
  6.         self.name = name
  7.         self.age = age
  8.         self.height = height
  9. def to_pinyin(stu):
  10.     print "这个print为什么不输出?"
  11.     return ''.join(chain.from_iterable(pinyin(stu.name, style=Style.TONE3)))
  12. studentList = [
  13.     Student("张三", 25, 190),
  14.     Student("小红", 22, 173),
  15.     Student("小张", 22, 177),
  16.     Student("王五", 25, 187),
  17.     Student("李四", 25, 172),
  18.     Student("小明", 22, 175)
  19. ]
  20. studentList.sort(key=lambda x: (-x.age, to_pinyin))
  21. for student in studentList:
  22.     print str(student.age) + " " + student.name + " " + str(student.height)
复制代码
输出结果:

很显然,这个结果,它不对!
随便用C#写了一个:
  1. List<Student> list = new List<Student>()
  2. {
  3.     new Student("张三",25),
  4.     new Student("小红",22),
  5.     new Student("小张",22),
  6.     new Student("王五",25),
  7.     new Student("李四",25),
  8.     new Student("小明",22),
  9. };
  10. //方法一,虽然写法繁琐,但思路清晰
  11. list.Sort((a, b) =>
  12. {
  13.     if (a.Age != b.Age)
  14.     {
  15.         return b.Age - a.Age;
  16.     }
  17.     else
  18.     {
  19.         return string.Compare(a.Name, b.Name);
  20.     }
  21. });
  22. //方法二,简捷清晰明了
  23. //list = list.OrderByDescending(a => a.Age).ThenBy(a => a.Name).ToList();
  24. foreach (var item in list)
  25. {
  26.     Console.WriteLine(item.Age + " " + item.Name);
  27. }
  28. Console.Read();
  29. class Student
  30. {
  31.     public string Name { get; set; }
  32.     public int Age { get; set; }
  33.     public Student(string name, int age)
  34.     {
  35.         Name = name;
  36.         Age = age;
  37.     }
  38. }
复制代码
输出结果:

结果是正确的。
Python正确的到底怎么写呢?
好吧,被移出博客园首页!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4