这是一个按照名称排序列表的示例代码:
# 原始列表
names = ['John', 'Alice', 'Bob', 'David', 'Catherine']
# 使用sorted函数按名称排序列表
sorted_names = sorted(names)
# 输出排序后的列表
for name in sorted_names:
print(name)
输出结果为:
Alice
Bob
Catherine
David
John
上述代码中,我们使用了Python内置的sorted()
函数来按照名称对列表进行排序。这个函数会返回一个新的已排序的列表,不会对原始列表进行修改。
如果想要按照名称的反向顺序进行排序,可以使用sorted(names, reverse=True)
。
如果列表中的元素是自定义对象,可以通过传递一个key
参数给sorted()
函数来指定排序的依据,例如按照对象的某个属性进行排序:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'Person({self.name}, {self.age})'
# 原始列表
people = [Person('John', 25), Person('Alice', 30), Person('Bob', 20)]
# 按照名称排序列表
sorted_people = sorted(people, key=lambda person: person.name)
# 输出排序后的列表
for person in sorted_people:
print(person)
输出结果为:
Person(Alice, 30)
Person(Bob, 20)
Person(John, 25)
上述代码中,我们通过key
参数传递了一个lambda函数,该函数指定了按照person.name
属性进行排序。
上一篇:按照名称排序的值应该显示出来。