Python如何根据两个字段进行排序?
Python如何根据两个字段进行排序?
写这个博客,就是为了吐槽Python!
对于这个问题,首先,我花了一天时间,没有解决!
当然是百度了,一搜,有很多博客,无一例外,都是垃圾!
有的,只排数组!实体类不考虑了?
有的,只排数字!不排中文?Python中文排序有问题知不知道?!
有的,只排中文!就排了一个字段?
通过百度,倒时很快写出来一个,因为始终不对,折腾一天!
# -*- coding: utf-8 -*-
from itertools import chain
from pypinyin import pinyin, Style
class Student:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
def to_pinyin(stu):
print "这个print为什么不输出?"
return "".join(chain.from_iterable(pinyin(stu.name, style=Style.TONE3)))
studentList = [
Student("张三", 25, 190),
Student("小红", 22, 173),
Student("小张", 22, 177),
Student("王五", 25, 187),
Student("李四", 25, 172),
Student("小明", 22, 175)
]
studentList.sort(key=lambda x: (-x.age, to_pinyin))
for student in studentList:
print str(student.age) + " " + student.name + " " + str(student.height)
输出结果:
很显然,这个结果,它不对!
随便用C#写了一个:
List<Student> list = new List<Student>()
{
new Student("张三",25),
new Student("小红",22),
new Student("小张",22),
new Student("王五",25),
new Student("李四",25),
new Student("小明",22),
};
//方法一,虽然写法繁琐,但思路清晰
list.Sort((a, b) =>
{
if (a.Age != b.Age)
{
return b.Age - a.Age;
}
else
{
return string.Compare(a.Name, b.Name);
}
});
//方法二,简捷清晰明了
//list = list.OrderByDescending(a => a.Age).ThenBy(a => a.Name).ToList();
foreach (var item in list)
{
Console.WriteLine(item.Age + " " + item.Name);
}
Console.Read();
class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
输出结果:
结果是正确的。
Python正确的到底怎么写呢?
好吧,被移出云海天首页!