class People: def __init__(self, name, city): self.name = name self.city = city def __str__(self): return "{}: {}".format(self.name, self.city) def moveto(self, newcity): self.city = newcity p1 = People("Tom", "New York") p2 = People("Jerry", "Paris") p3 = People("Alice", "London") p4 = People("Bob", "Beijing") people_list = [p1, p2, p3, p4] people_list.sort(key=lambda x: x.city) for p in people_list: print(p) 解释一下此代码
时间: 2024-04-05 18:29:54 浏览: 353
这段代码定义了一个名为People的类,表示一个人,每个人有一个名字和所在城市。类中有一个__str__方法,返回一个字符串,描述这个人的名字和所在城市。还有一个moveto方法,可以将这个人的所在城市改为新的城市。
在主程序中,创建了四个People对象,并将它们放入一个列表中。使用sort函数,按照每个人所在城市的字母顺序对人进行排序。然后遍历人的列表,打印每个人的描述字符串,这些字符串按照城市字母顺序排列。
相关问题
class Person: def __init__(self, name, age): self.name = name self.age = age
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
class Student(Person):
def __init__(self, name, age, major):
super().__init__(name, age)
self.major = major
def study(self):
print(f"I am studying {self.major}.")
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
def teach(self):
print(f"I am teaching {self.subject}.")
s = Student("John", 20, "Computer Science")
s.introduce() # Output: My name is John and I am 20 years old.
s.study() # Output: I am studying Computer Science.
t = Teacher("Jane", 35, "Math")
t.introduce() # Output: My name is Jane and I am 35 years old.
t.teach() # Output: I am teaching Math.
class PhoneDirectory: def __init__(self): self.tel_hash = {} self.name_hash = {}如何用链表表达
在Python中,`tel_hash` 和 `name_hash` 是两个字典,用于存储电话号码(键)和对应的名字(值)。如果你想使用链表来表示这些数据结构,我们需要转换为双向链表,因为字典本质上已经是哈希表,提供了非常快的查找性能。但在链表中,插入、删除操作可能会慢一些。
首先,定义一个节点类(Node)来构建链表:
```python
class Node:
def __init__(self, tel, name=None):
self.tel = tel
self.name = name
self.prev = None
self.next = None
class LinkedListPhoneDirectory:
def __init__(self):
self.head = None
self.tail = None
# 插入方法
def insert(self, tel, name):
if not self.head:
self.head = Node(tel, name)
self.tail = self.head
else:
new_node = Node(tel, name)
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
# 查找方法(这里只简单地遍历链表)
def find_by_tel(self, tel):
current = self.head
while current and current.tel != tel:
current = current.next
return current
# 示例
phone_directory = LinkedListPhoneDirectory()
phone_directory.insert("123", "Alice")
```
在这个实现中,`LinkedListPhoneDirectory` 类有一个头节点 `head` 和尾节点 `tail`,分别代表链表的开始和结束。`insert` 方法用于在链表末尾添加新条目,`find_by_tel` 方法用于根据电话号码查找对应的节点。
阅读全文