首页 > 解决方案 > 试图从用户输入中获取最接近已知键的值 | numpy.core_exception

问题描述

我正在尝试编写基于文本的体育游戏,该游戏的一部分是根据将用户输入与已知值进行比较来决定谁赢得提示,并根据哪个用户最接近来决定获胜者。

我使用 NumPy 将包含值的列表转换为数组,然后找到每个值与 K 的绝对差并从中获得最小值

我收到此错误:

Traceback (most recent call last):
  File "/Users/***/PycharmProjects/MyFirsyPycharm/Sports_Game/basketballgame.py", line 33, in <module>
    tipoff(player_one_tip, player_two_tip)
  File "/Users/***/PycharmProjects/MyFirsyPycharm/Sports_Game/basketballgame.py", line 11, in tipoff
    tipoff_winner = closest(tipoff_value, 50)
  File "/Users/***/PycharmProjects/MyFirsyPycharm/Sports_Game/basketballgame.py", line 6, in closest
    idx = (np.abs(lst - K)).argmin()
numpy.core._exceptions.UFuncTypeError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U3'), dtype('<U3')) -> dtype('<U3')

我的代码如下:

import numpy as np

def closest(lst, K):
    lst = np.asarray(lst)
    idx = (np.abs(lst - K)).argmin()
    return lst[idx]

def tipoff(p_one, p_two):
    tipoff_value = [p_one, p_two]
    tipoff_winner = closest(tipoff_value, 50)
    print(tipoff_winner)
    if (tipoff_winner == p_one):
        print("Player one has selected the correct value and has won the tip off")
    elif (tipoff_winner == p_two):
        print("PLayer two has selected the correct choice and won the tip_off")


print("Welcome to NBA Basketball 1 on 1!")

player_one = input("Player one, what is your name?")
print(player_one)

player_two = input("Player two, what is your name?")
print(player_two)

print(f"Welcome today's game is \n {player_one} \nvs \n  {player_two}")

player_one_tip = input("Player one, select a number between 1 and 100")

player_two_tip = input("Player two, select a number between 1 and 100")

tipoff(player_one_tip, player_two_tip)

不要求答案,但有人可以指出我缺少什么吗?或者请让我知道我是否以完全错误的方式去做

标签: pythonpython-3.xnumpy

解决方案


那是因为您input将数字作为字符串。

您应该更改为:

player_one_tip = int(input("Player one, select a number between 1 and 100"))

player_two_tip = int(input("Player two, select a number between 1 and 100"))

推荐阅读