检查列表是否包含 4 个具有相同值的元素

发布于 2024-10-08 20:13:37 字数 1279 浏览 2 评论 0原文

所以我再次陷入了一个新手问题:D

我正在尝试将一个基于文本的钓鱼游戏与计算机混合在一起。

好的,一张卡片实际上是来自两个列表的元素元组。

suits = ['Clubs', 'Diamonds', 'Spade', 'Hearts']
ranks = [None, 'ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king']

然后将其添加到一副牌中并洗牌等等,然后发到手上。 (我认为大部分内容是从 thinkpython 书中获得的。在这个过程中学到了很多关于类结构和继承的知识。)

所以一只手可能看起来像这样

['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']

正如你所看到的,那只手包含四个相同的等级,所以这是 1 分玩家。 但是我如何检查手牌是否包含排名列表中任何项目的四个实例? 我是否必须迭代列表中的每个项目,或者是否有一些干净简单的方法?


编辑
非常感谢大家的回答。 :D 但是当我尝试对手中的物品使用“拆分”时,出现属性错误。 我想我应该发布更多我正在运行的代码。

完整代码和回溯在这里
http://pastebin.com/TwHkrbED

Card 中方法的定义方式是否有问题? 我已经花了几个小时尝试让它工作,但没有运气。

编辑2
对套牌生成部分进行了一些更改。现在整个牌组是一个元组列表和更少的代码。

thedeck=[]
class Deckofcards:
    suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
    ranks = ['Ace', '2', '3', '4', '5', 
        '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
    def __init__(self):
        for i in self.suits:
            for a in self.ranks:
                thedeck.append((i, a))

似乎另一种方式过于复杂,但我不知道。我明天会看看进展如何,添加实际的游戏部分。

So I'm stuck on a newbie problem once more :D

I'm trying to mash together a text based game of go-fish against the computer.

Ok so 1 card is actually a tuple of elements from two lists.

suits = ['Clubs', 'Diamonds', 'Spade', 'Hearts']
ranks = [None, 'ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king']

Then that is added to a deck and shuffled and whatnot and then dealt into hands. (got most of it from the book thinkpython i think. Learned a lot about class structure and inheritance in the process.)

So one hand might look like this

['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']

As you can see that hand contains four of the same rank so that's 1 point for the player.
But how would I check if the hand contains four instances of any item in the ranks list?
Do I have to iterate through each item in the list or there some clean and simple way to it?


EDIT
Thanks a lot for all the answers guys. :D
But I'm getting an attribute error when I try to use 'split' on the items in the hand.
Guess I should have posted more of the code I'm running.

Full code and traceback here
http://pastebin.com/TwHkrbED

Is there something wrong with how the methods are defined in Card?
I've been hacking around for hours trying to make it work, but no luck.

EDIT2
Made some changes to the deck generating part. Now the whole deck is a list of tuples and a lot less code.

thedeck=[]
class Deckofcards:
    suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
    ranks = ['Ace', '2', '3', '4', '5', 
        '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
    def __init__(self):
        for i in self.suits:
            for a in self.ranks:
                thedeck.append((i, a))

Seems like the other way was overly complicated, but idk. I'll see how it goes tomorrow, adding the actual game parts.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

旧情别恋 2024-10-15 20:13:37

我可能建议稍微重构一下:将手中的每张牌表示为(rank,suit)的元组。因此,您的示例手牌将是:

hand = [('2', 'Clubs'),
        ('king', 'Diamonds'),
        ('2', 'Diamonds'),
        ('2', 'Spades'),
        ('2', 'Hearts')]

然后我建议使用几个辅助函数来帮助您确定手牌的价值:

from collections import defaultdict

def get_counts(hand):
    """Returns a dict mapping card ranks to counts in the given hand."""
    counts = defaultdict(int)
    for rank, suit in hand:
        counts[rank] += 1
    return counts

def get_points(hand):
    """Returns the number of points (ie, ranks with all 4 cards) in the given
    hand."""
    return sum(1 for count in get_counts(hand).itervalues() if count == 4)

编辑: 切换到在 sum 中使用 sum code>get_points 函数,这对我来说似乎更清楚。

使用这些函数和您给出的示例手,您将得到如下输出:

>>> get_counts(hand)
defaultdict(<type 'int'>, {'king': 1, '2': 4})

>>> get_points(hand)
1

I might suggest a slight refactoring: Represent each card in a hand as a tuple of (rank, suit). So your example hand would be:

hand = [('2', 'Clubs'),
        ('king', 'Diamonds'),
        ('2', 'Diamonds'),
        ('2', 'Spades'),
        ('2', 'Hearts')]

Then I'd suggest a couple of auxiliary functions to help you determine the value of a hand:

from collections import defaultdict

def get_counts(hand):
    """Returns a dict mapping card ranks to counts in the given hand."""
    counts = defaultdict(int)
    for rank, suit in hand:
        counts[rank] += 1
    return counts

def get_points(hand):
    """Returns the number of points (ie, ranks with all 4 cards) in the given
    hand."""
    return sum(1 for count in get_counts(hand).itervalues() if count == 4)

Edit: Switched to using sum in the get_points function, which seems clearer to me.

Working with these functions and the example hand you gave, you get output like so:

>>> get_counts(hand)
defaultdict(<type 'int'>, {'king': 1, '2': 4})

>>> get_points(hand)
1
年华零落成诗 2024-10-15 20:13:37

这是一种方法:

x = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']
ranks = [i.split()[1] for i in x]
fourofakind = any(ranks.count(i)==4 for i in set(ranks))

如果手中有四张相同等级的牌,则 fourofakind 为 True。

Here's one way:

x = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']
ranks = [i.split()[1] for i in x]
fourofakind = any(ranks.count(i)==4 for i in set(ranks))

fourofakind is then True if there are four cards of the same rank in the hand.

忆沫 2024-10-15 20:13:37

如果您正在寻找扩展类型的功能:

hand = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']
hand_ranks = [i.split()[1] for i in x]
fourofakind = {}
for i in set(hand_ranks):
    fourofakind[i] = (hand_ranks.count(i) == 4)

会给您一个 dict() 映射卡牌等级(手中的牌)到您是否有 4 个该等级。

If you are looking for an extended kind of functionality:

hand = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']
hand_ranks = [i.split()[1] for i in x]
fourofakind = {}
for i in set(hand_ranks):
    fourofakind[i] = (hand_ranks.count(i) == 4)

Would give you a dict() mapping card rank (of cards in the hand) to whether you have 4 of that rank.

深爱不及久伴 2024-10-15 20:13:37

比贾斯汀的更通用一点:

suits = ['Clubs', 'Diamonds', 'Spade', 'Hearts']
ranks = [None, 'ace', '2', '3', '4', '5', '6', '7', \
'8', '9', '10', 'jack', 'queen', 'king']

hand = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts king']
rankshand = [i.split()[1] for i in hand]

fourofakind = [hr for hr in ranks if rankshand.count(hr)==4]
threeofakind = [hr for hr in ranks if rankshand.count(hr)==3]
pair = [hr for hr in ranks if rankshand.count(hr)==2]

fourofakind
[]
threeofakind
['2']
pair
['king']

能够查看哪个等级有该套装。

A bit more general than Justin's:

suits = ['Clubs', 'Diamonds', 'Spade', 'Hearts']
ranks = [None, 'ace', '2', '3', '4', '5', '6', '7', \
'8', '9', '10', 'jack', 'queen', 'king']

hand = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts king']
rankshand = [i.split()[1] for i in hand]

fourofakind = [hr for hr in ranks if rankshand.count(hr)==4]
threeofakind = [hr for hr in ranks if rankshand.count(hr)==3]
pair = [hr for hr in ranks if rankshand.count(hr)==2]

fourofakind
[]
threeofakind
['2']
pair
['king']

With the ability to see which rank has the set.

怪我入戏太深 2024-10-15 20:13:37

Python 2.7 中添加到标准库 collections 模块中的新内置 Counter 类使这变得相当简单。

suits = ['Clubs', 'Diamonds', 'Spade', 'Hearts']
ranks = [None, 'ace', '2', '3', '4', '5', '6', '7',
         '8', '9', '10', 'jack', 'queen', 'king']
hand = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']

from collections import Counter

counts = Counter(card.split()[1] for card in hand)
four_of_a_kind = [rank for rank,count in counts.iteritems() if count == 4]
print 'four_of_a_kind:', four_of_a_kind
# four_of_a_kind: ['2']

The new built-in Counter class added in Python 2.7 to the standard library collections module makes this fairly easy.

suits = ['Clubs', 'Diamonds', 'Spade', 'Hearts']
ranks = [None, 'ace', '2', '3', '4', '5', '6', '7',
         '8', '9', '10', 'jack', 'queen', 'king']
hand = ['Clubs 2', 'Diamonds king', 'Diamonds 2', 'Spades 2', 'Hearts 2']

from collections import Counter

counts = Counter(card.split()[1] for card in hand)
four_of_a_kind = [rank for rank,count in counts.iteritems() if count == 4]
print 'four_of_a_kind:', four_of_a_kind
# four_of_a_kind: ['2']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文