【发布时间】:2015-02-18 07:03:07
【问题描述】:
在这里,我试图将社交媒体个人资料模拟为“个人资料”类,其中您有姓名、一群朋友以及添加和删除朋友的能力。我想做一个方法,调用时会按字母顺序打印朋友列表。
问题:我收到一条警告,提示我无法对不可排序的类型进行排序。 Python 将我的实例变量视为“配置文件对象”,而不是我可以排序和打印的列表。
这是我的代码:
class Profile(object):
"""
Represent a person's social profile
Argument:
name (string): a person's name - assumed to uniquely identify a person
Attributes:
name (string): a person's name - assumed to uniquely identify a person
statuses (list): a list containing a person's statuses - initialized to []
friends (set): set of friends for the given person.
it is the set of profile objects representing these friends.
"""
def __init__(self, name):
self.name = name
self.friends = set()
self.statuses = []
def __str__(self):
return self.name + " is " + self.get_last_status()
def update_status(self, status):
self.statuses.append(status)
return self
def get_last_status(self):
if len(self.statuses) == 0:
return "None"
else:
return self.statuses[-1]
def add_friend(self, friend_profile):
self.friends.add(friend_profile)
friend_profile.friends.add(self)
return self
def get_friends(self):
if len(self.friends) == 0:
return "None"
else:
friends_lst = list(self.friends)
return sorted(friends_lst)
在我填写朋友列表(来自测试模块)并调用 get_friends 方法后,python 告诉我:
File "/home/tjm/Documents/CS021/social.py", line 84, in get_friends
return sorted(friends_lst)
TypeError: unorderable types: Profile() < Profile()
为什么我不能简单地将对象类型转换为列表形式?我应该怎么做才能让 get_friends 返回按字母顺序排序的朋友列表?
【问题讨论】:
-
简单解决方案:
return sorted(friends_lst, key=lambda x:x.name) -
除此之外,
list([])和set({})是多余的,[]和set()就足够了 -
@AshwiniChaudhary 我确实在使用 python3。您上面的建议仍然会打印对象及其在内存中的位置,而不是列表。为什么会这样?
-
@ThomasMatthew 因为你还没有定义
__repr__方法。 list、tuple、dict 等容器通常显示对象的repr() 版本。 -
@ThomasMatthew 也正如 IfLoop 指出的那样,不要将
{}与集合混淆。这是一个非常常见的错误,要获得一个空集,请使用set()。虽然set({})有效,但这不是正确的方法。