<p>最好的方法是在(我猜)类<code>Contact</code>中实现<a href="https://docs.python.org/2/reference/datamodel.html#object.__lt__" rel="nofollow">the rich comparison magic methods</a>:</p>
<pre><code>class Contact(object):
def __init__(self, first_name, last_name=""):
self.first_name = first_name
self.last_name = last_name
def __repr__(self): # to make the demo clearer!
if not self.last_name:
return str(self.first_name)
return "{0.first_name} {0.last_name}".format(self)
def __eq__(self, other):
return (self.first_name == other.first_name and
self.last_name == other.last_name)
def __lt__(self, other):
if self.last_name and other.last_name:
if self.last_name == other.last_name:
return self.first_name < other.first_name
return self.last_name < other.last_name
else:
if other.last_name:
return self.first_name < other.last_name
return self.first_name < other.first_name
</code></pre>
<p>现在您可以只使用<code>sorted</code>和<code>list.sort</code>而不带参数:</p>
<pre><code>>>> contacts_list = [Contact("Luke"), Contact("Riyaan"), Contact("Amanda", "Benson")]
>>> sorted(contacts_list)
[Amanda Benson, Luke, Riyaan]
</code></pre>