7

我有一个列表列表:

>>> a = [['3D'], ['3D', '4D', '5D'], ['4C'], ['2C'],['4C', '4D'], ['4D'], ['5D'], \
... ['JC'], ['JC', 'JS'], ['JS']]

您可能会注意到这是卡片值,即 C= 俱乐部等。J = 杰克等。我还有一个参考列表:

>>> confrom = {'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, \
... '0':10, 'J':11, 'Q':12, 'K':13, 'A':14, '2':15}

当我在玩一个最大值为 2 的纸牌游戏时。按列表长度排序,我这样做:

>>> a = sorted(a, key = lambda x: len(x))
>>> a
... [['3D'], ['4C'], ['4D'], ['2C'], ['5D'], ['JC'], ['JS'], ['4C', '4D'], ['JC', 'JS'], ['3D', '4D', '5D']]

我还需要根据它们的字典值对它们进行排序,所以我的结果列表将是:

>>> [['3D'], ['4C'], ['4D'], ['5D'], ['JC'], ['JS'], ['2C'], ['4C', '4D'], ['JC', 'JS'], ['3D', '4D', '5D']]

目前这是一个非常简单的实现,但我希望能够以更复杂的方式对其进行排序。

4

2 回答 2

10

尝试这个:

sorted(a, key = lambda x: (len(x), [confrom[card[0]] for card in x]))

ideone

于 2012-05-24T04:15:57.460 回答
2

这可能是何时从 Python 中的基本数据结构转换为类的一个非常好的示例。

考虑:

values = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
suits = ('H', 'C', 'D', 'S')
sRep = {'H':'Hearts', 'C':'Clubs', 'D':'Diamonds', 'S':'Spades'}
ranks = {'2':15, '3':3, '4':4,'5':5,'6':6,'7':7,'8':8,
         '9':9, '0':10, '0':10, 'J':11, 'Q':12, 'K':13, 'A':14 }

class Card:
    def __init__(self, value, suit):
        value=str(value)
        self.value, self.suit = value.upper(), suit.upper()
        self.rSuit = sRep[suit.upper()]
        self.rank = ranks[value.upper()]

    def __repr__(self):
        return "%s of %s" % (self.value, self.rSuit)

    def __cmp__(self,other):
        if self.rank > other.rank: return 1
        if self.rank < other.rank: return -1    
        if self.value > other.value: return 1
        if self.value < other.value: return -1
        if self.rSuit > other.rSuit: return 1
        if self.rSuit < other.rSuit: return -1
        return 0

尝试一些卡片:

c1=Card(2,'s')     
c2=Card(4,'d')

if c1>c2:
    print "A", c1, "beats a", c2
elif c2>c1:    
    print "A", c2, "beats a", c1
else:
    print "Same..."    

这打印:

A 2 of Spades beats a 4 of Diamonds

由于我们在类中定义了排序顺序,因此复杂的排序很容易,基于不同游戏的排名也很容易。

以您的卡片列表为例:

a = [['3D'], ['3D', '4D', '5D'], ['4C'], ['2C'],['4C', '4D'], ['4D'], ['5D'], ['JC'], ['JC', 'JS'], ['JS']]  

print sorted([Card(c[0],c[1]) for e in a for c in e])

印刷:

[3 of Diamonds, 3 of Diamonds, 4 of Clubs, 4 of Clubs, 4 of Diamonds, 
 4 of Diamonds, 4 of Diamonds, 5 of Diamonds, 5 of Diamonds, J of Clubs, 
 J of Clubs, J of Spades, J of Spades, 2 of Clubs]

再做一点工作,您就可以定义手以及什么手击败另一只手。

您可以在经典 Python 书籍《如何像计算机科学家一样思考:使用Python学习》中阅读有关此示例的更多信息。

于 2012-05-24T05:46:35.390 回答