简体   繁体   English

在列表中获得最高价值的卡

[英]Getting highest value card in list

I have a list of cards: 我有一张卡片清单:

    hand = ["KC", "QC", "4C", "0S"]

And I always want to get the highest card in terms of rank, like in this list 我总是希望在排名方面获得最高的牌,就像在这个列表中一样

    rank_cards = ["2", "3", "4", "5", "6", "7", "8", "9", "0", "J", "Q", "K", "A"]

The highest card in this case would be: 在这种情况下,最高的卡将是:

    "KC"

How can I do this for any sort of hand I get? 我怎样才能为我得到的任何一只手做到这一点?

I was thinking of using a dictionary to rank cards in terms of index, like this: 我正在考虑使用字典来按照索引对卡进行排名,如下所示:

    d = {}
    for i, c in enumerate(rank_cards):
        d[c] = i

Is there a better way to do this? 有一个更好的方法吗?

Thanks 谢谢

You could use the max built-in function and use a custom key function. 您可以使用max内置函数并使用自定义key功能。

>>> max(hand, key=lambda c: rank_cards.index(c[0]))
'KC'

If you want to sort the entire hand in descending order based on rank 如果要根据等级按降序对整个手进行排序

>>> hand.sort(key=lambda c: rank_cards.index(c[0]), reverse=True)

If you wanted slightly better performance by pre-computing indexes (basically, your solution, but one-lined in a dictionary comprehension). 如果您希望通过预先计算索引(基本上是您的解决方案,但在字典理解中排成一行)稍微提高性能。

>>> rank_cards_map = {c: i for i, c in enumerate(rank_cards)}
>>> max(hand, key=lambda c: rank_cards_map[c[0]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM