Python,如何对对象列表进行排序? [英] Python, how to sort list of object?
问题描述
我有一个看起来像这样的对象列表.
I have a list of object that looks like this.
hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ]
Card(10,'H)在这里不是元组,而是对象.如果列表中的每个项目都是元组形式的,我知道如何对该列表进行排序,
Card(10, 'H) here is not a tuple, but an object. I know how to sort this list if each item in the list was in a form of tuple, like this,
hand = sorted(hand, key = lambda x: x[0])
但是我不知道如何对对象列表进行排序.我想按第一个输入值(即Card()中的数字)对列表进行排序
but I have no idea how to sort a list of objects. I want to sort my list by the first input value, which is the number in Card()
我该怎么做?
这是Card()的定义.
Here's the definition of Card().
class Card(object):
RANKS = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
SUITS = ('C', 'D', 'H', 'S')
def __init__(self, rank=12, suit='S'):
if (rank in Card.RANKS):
self.rank = rank
else:
self.rank = 12
if (suit in Card.SUITS):
self.suit = suit.upper()
else:
self.suit = 'S'
def __str__(self):
if (self.rank == 14):
rank = 'A'
elif (self.rank == 13):
rank = 'K'
elif (self.rank == 12):
rank = 'Q'
elif (self.rank == 11):
rank = 'J'
else:
rank = str(self.rank)
return rank + self.suit
def __eq__(self, other):
return (self.rank == other.rank)
def __ne__(self, other):
return (self.rank != other.rank)
def __lt__(self, other):
return (self.rank < other.rank)
def __le__(self, other):
return (self.rank <= other.rank)
def __gt__(self, other):
return (self.rank > other.rank)
def __ge__(self, other):
return (self.rank >= other.rank)
推荐答案
想法仍然相同.只是您将在类对象中寻找特定的属性.
The idea is still the same. Just that you will be looking for a specific attribute in the class object.
对于您的卡类,您可以执行以下操作:
For your card class, you could do something like this:
hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ]
那你可以做
sorted_cards = sorted(hand, key=lambda x: x.rank)
输出看起来像这样:
>>> [card.number for card in sorted_cards]
[2, 10, 12, 13, 14]
这篇关于Python,如何对对象列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!