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

numpy随机选值拼接字符串报UFuncTypeError问题求助

报错根因
  • 你调用np.random.choice时传入了第二个参数1,此时返回结果是一维numpy字符串数组,而非Python原生字符串。Python的+运算符不支持原生字符串和numpy数组直接拼接,因此触发类型错误。
  • 报错信息中提到的ufunc 'add' did not contain a loop with signature matching types就是numpy未实现字符串与numpy数组相加逻辑的明确提示。
修复方法

有两种可直接落地的修改方案:

  1. 直接省略np.random.choice的第二个参数,此时函数会默认返回单个随机元素而非数组:
def generateHand():
    cardOne = ("one", "two", 'three', "four", "five", "six", 'seven', "eight", "nine", "10", 
    "jack", "queen", "king")
    suits = ["spades", "diamonds", "hearts", "clubs"]
    suitUse = np.random.choice(suits)
    cardOneVar = np.random.choice(cardOne)
    print("A" + cardOneVar + "Of" + suitUse)
  1. 保留参数1,通过索引取数组中的第一个元素转为原生字符串:
suitUse = np.random.choice(suits, 1)[0]
cardOneVar = np.random.choice(cardOne, 1)[0]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:54:07