You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于全名称从扑克牌列表中找出价值最高的牌?

问题解释与解决方案

错误原因

你代码里的lambda c: card_order.index(c[0])犯了一个基础错误:c[0]取的是每张牌字符串的第一个字符(比如"king of diamonds"的第一个字符是'k'),但card_order列表里存储的是完整的牌面值单词(比如"king"),所以程序会找不到'k',进而抛出ValueError: 'k' is not in the list。

你提到的\b正则整词匹配完全用不上,问题核心是你没有正确提取出牌的面值部分,而非匹配问题。

解决方案

方法1:提取完整牌面值(基础版)

每张牌的格式是"[面值] of [花色]",可以用split()方法将字符串按空格分割,取分割后的第一个元素(也就是牌面值),再去card_order里找对应的索引。

修改后的代码:

hand = ["king of diamonds","queen of spades","three of clubs","six of clubs","ace of hearts"]
card_order = ["ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king"]

print(max(hand, key=lambda c: card_order.index(c.split()[0])))

运行后会输出正确结果:king of diamonds

方法2:用字典优化查找效率(进阶版)

list.index()每次查找都要遍历整个列表,当牌的数量较多时效率较低。可以把card_order改成字典,键是牌面值,值是对应的优先级数值,这样查找速度会更快:

hand = ["king of diamonds","queen of spades","three of clubs","six of clubs","ace of hearts"]
# 数值越大,牌的优先级越高
card_order = {"ace": 1, "two": 2, "three": 3, "four": 4, "five": 5,
              "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
              "jack": 11, "queen": 12, "king": 13}

print(max(hand, key=lambda c: card_order[c.split()[0]]))

内容的提问来源于stack exchange,提问作者Blink

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 08:42:12