python - 试图从用户输入中获取最接近已知键的值 | 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)
不要求答案,但有人可以指出我缺少什么吗?或者请让我知道我是否以完全错误的方式去做
解决方案
那是因为您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"))
推荐阅读
- android - 如何使用复选框获取选定项目计数,选择/取消选择 Recyclerview 中的所有项目?
- java - .xsl 文件不能通过浏览器从 tomcat7 下载
- css - RTLCSS 框架如何在 Visual Studio 2017 的 WebEssentials 中工作。?如何在 Visual Studio 2017 中集成 RLCSS 框架
- php - Laravel 中的自定义验证消息
- haskell - Haskell Gloss 和 STM 并发集成
- json - 无法在 Azure 逻辑应用程序中解析具有空内容的 xml
- go - 两种 gin 模式 debug 和 release 有什么区别?
- hyperledger-fabric - 我们在哪里添加外部 go 依赖项,以便在使用 fabric-java-sdk 部署链代码时,链代码构建器会相应地选择它?
- dialogflow-es - Dialogflow Intents 不符合正确意图的后续行动
- node.js - 无法从 lambda Nodejs 连接到 EC2 Postgres DB