重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
# -*- coding: utf-8 -*-
# 需求:年龄倒序,姓名正序
from itertools import chain
from pypinyin import pinyin, Style
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def to_pinyin(stu):
lst = pinyin(stu.name, style=Style.TONE3) # 例:[['zhang1'], ['san1']]
print(lst)
iterator = chain.from_iterable(lst) # 迭代器
iterator_for_print = chain.from_iterable(lst) # 迭代器
print(iterator_for_print)
for item in iterator_for_print:
print(item)
# 写法一
return ''.join(iterator)
# 写法二
# return ''.join(chain.from_iterable(pinyin(stu.name, style=Style.TONE3)))
studentList = [
Student("张三", 25),
Student("小红", 22),
Student("王五", 25),
Student("小张", 22),
Student("李四", 25),
Student("小明", 22)
]
# 写法一
# studentList.sort(key=lambda stu: pinyin(stu.name, style=Style.TONE3))
# 写法二
studentList.sort(key=lambda stu: to_pinyin(stu))
studentList.sort(key=lambda stu: stu.age, reverse=True)
print("排序结果:")
for student in studentList:
print(str(student.age) + " " + student.name)
# -*- coding: utf-8 -*-
# 需求:年龄倒序,姓名正序
from itertools import chain
from pypinyin import pinyin, Style
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def to_pinyin(stu):
lst = pinyin(stu.name.decode("utf-8"), style=Style.TONE3) # 例:[['zhang1'], ['san1']]
print(lst)
iterator = chain.from_iterable(lst) # 迭代器
iterator_for_print = chain.from_iterable(lst) # 迭代器
print(iterator_for_print)
for item in iterator_for_print:
print(item)
# 写法一
return ''.join(iterator)
# 写法二
# return ''.join(chain.from_iterable(pinyin(stu.name.decode("utf-8"), style=Style.TONE3)))
studentList = [
Student("张三", 25),
Student("小红", 22),
Student("王五", 25),
Student("小张", 22),
Student("李四", 25),
Student("小明", 22)
]
# 写法一
# studentList.sort(key=lambda stu: pinyin(stu.name.decode("utf-8"), style=Style.TONE3))
# 写法二
studentList.sort(key=lambda stu: to_pinyin(stu))
studentList.sort(key=lambda stu: stu.age, reverse=True)
print("排序结果:")
for student in studentList:
print(str(student.age) + " " + student.name)
List list = new List()
{
new Student("张三", 25),
new Student("小红", 22),
new Student("王五", 25),
new Student("小张", 22),
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程序员会说,这还不简单?
但是对于新手来说,非常不人性化,非常浪费时间。
我作为一个Python新手,就写个简单的排序程序,花了很长时间才学会怎么写,当然,确实没有去看文档,只通过百度以及在技术群里问,但是没有一个一口答出正确答案,最后自己摸索成功。
有人说Python2忘的差不多了,C#就不会忘。
用到pypinyin库时,还不习惯看pypinyin库的源码,pinyin方法的注释非常详细,不过没有C#这种强类型的语言看起来方便。
对比C#,Python的代码确实相对简捷。
成都创新互联公司专注于龙游企业网站建设,自适应网站建设,商城网站定制开发。龙游网站建设公司,为龙游等地区提供建站服务。全流程按需网站制作,专业设计,全程项目跟踪,成都创新互联公司专业和态度为您提供的服务