Python列表count方法异常:判断扑克同花时返回0而非预期的5
问题分析与解决方案
错误原因
self.hand.count(self.hand[-1][-1]) 是在列表中查找完全等于'h'的元素,但你的手牌列表里都是'Jh'、'10h'这类带牌面的字符串,没有单独的'h'元素,所以count方法返回0,导致同花判断失败。
修正思路
需要验证每张牌的最后一个字符(花色)是否都和最后一张牌的花色一致。用all()函数遍历所有手牌是更高效的方式——只要有一张牌花色不匹配,就直接返回False,无需统计总数。
修正后的代码
poker_hand.py
class PokerHand: def __init__(self, hand): self.hand = hand self.flush = False def is_flush(self): if not self.hand: self.flush = False return target_suit = self.hand[-1][-1] # 检查所有牌的花色是否与目标花色一致 if all(card[-1] == target_suit for card in self.hand): self.flush = True
main.py(无需修改)
from poker_hand import PokerHand, test_hand_one, test_hand_two test_hand_one = ['Jh', 'Qh', 'Kh', 'Ah', '10h'] if __name__ == '__main__': hand_one = PokerHand(test_hand_one) hand_one.is_flush() print(hand_one.flush)
运行后会输出True,符合同花判断的预期。
内容的提问来源于stack exchange,提问作者Nicholas Crook
相关产品推荐
相关产品推荐

