Python字典get()方法存在键时仍计算默认值引发异常问题
字典get()方法默认值提前求值引发的ValueError问题
问题的核心在于:Python函数的所有实参在传递给函数前都会被完全求值,包括dict.get()方法的默认值参数。哪怕目标键已经存在于字典中,默认值表达式也会先被计算,这就导致了意外错误。
看你的二十一点计算代码,当处理'J'时,虽然'J'在values字典里有对应值,但values.get(card, int(card))中的int(card)还是会先被执行,而int('J')无法转换为整数,直接抛出ValueError。
解决方法
有两种常用的修复思路:
思路1:用条件表达式替代get()
先判断键是否存在于字典中,不存在时再执行类型转换,避免无效的计算:
def blackjack(cards): values = {"J" : 10, "Q" : 10, "K" : 10} aces = cards.count("A") cards = [i for i in cards if i != "A"] hand = 0 for card in cards: # 先检查键存在性,再决定取值方式 hand += values[card] if card in values else int(card) while aces > 0: if hand + aces > 11: return hand + aces elif hand < 11: hand += 11 else: hand += 1 aces -= 1 return hand cards = ['J','3'] print(blackjack(cards)) # 输出13
思路2:预先填充数字牌的映射
把2-10的数字牌也提前加入字典,这样就不需要额外的类型转换,直接通过键取值即可:
def blackjack(cards): values = {"J" : 10, "Q" : 10, "K" : 10} # 预先添加数字牌的映射 for num in range(2, 11): values[str(num)] = num aces = cards.count("A") cards = [i for i in cards if i != "A"] hand = 0 for card in cards: hand += values[card] while aces > 0: if hand + aces > 11: return hand + aces elif hand < 11: hand += 11 else: hand += 1 aces -= 1 return hand cards = ['J','3'] print(blackjack(cards)) # 输出13
关键知识点回顾
Python的参数求值是严格的左到右求值,所有函数实参(包括默认参数)在函数调用前都会被计算完成。这意味着dict.get(key, default)中的default表达式无论key是否存在,都会先被执行。如果默认值的计算有副作用或者可能抛出异常,就会引发意外问题,此时应该改用条件判断或者提前预处理数据来避免。
内容的提问来源于stack exchange,提问作者dobbbb
相关产品推荐
相关产品推荐

