如何将输入函数中的文本字符串转换为整数?



我正在尝试写一个非常简单的程序为石头,布,剪刀游戏。我生成一个随机整数,即对手的走法,然后输入我自己的猜测。以整数形式。然后,我将这两个整数组合成一个列表,并根据结果矩阵测试这些坐标。

我已经转换了"岩石","纸张"。和";scissors"将其分成如下整数:

guess = input("Enter your move: "rock", "paper", "scissors", or "quit": n")
if guess == "rock":
guess = 0
if guess == "paper":
guess = 1
if guess == "scissors":
guess = 2
if guess == "quit":
break
weapon = random.randint(0, 2)  # 0 is rock, 1 is paper, 2 is scissors
outputGuess = (int(guess), int(weapon))

是否有办法摆脱所有的if语句?我尝试了以下方法,但它不起作用:

guess = input("Enter your move: "rock", "paper", "scissors", or "quit": n")
"rock" = 0
"paper" = 1
"scissors" = 2
weapon = random.randint(0, 2)  # 0 is rock, 1 is paper, 2 is scissors
outputGuess = (int(guess), int(weapon))

谢谢!

或者,您可以使用一行if statement。语法为result if condition else result

guess = 0 if guess=='rock' else 1 if guess=='paper' else 2 if guess=='scissors' else break

检查它是否为rock,否则检查它是否为paper,否则检查它是否为scissors,否则检查它是否为break因为它不是猜测

已经有两个很好的答案可以解决这个问题,但这里是我的解决方案。您可以将字符串放入一个名为options的列表中,然后获得guess的索引。

guess = input("Enter your move: "rock", "paper", "scissors", or "quit": n")
options = ["rock", "paper", "scissors"]
if guess in options:
guess = options.index(guess)
else:
break
weapon = random.randint(0, 2)  # 0 is rock, 1 is paper, 2 is scissors
outputGuess = (guess, weapon)

我在outputGuess行中删除了int(),因为randint()index()函数都返回一个整数。

正如@SharathNS建议的那样,您可以尝试探索枚举的使用方法,以便在一个地方定义所有内容,从而可以更好地控制可能的选项。

from enum import Enum
import random

class GameOption(Enum):
rock = 0
paper = 1
scissors = 2
GAME_OPTION_KEYS = [option.name for option in GameOption]
GAME_OPTION_VALUES = [option.value for option in GameOption]
while (guess := input(f"Enter your move: {GAME_OPTION_KEYS}, or "quit": n")) != "quit":
weapon = random.choice(GAME_OPTION_VALUES)
outputGuess = (GameOption[guess], "vs", GameOption(weapon))
print(outputGuess)

输出
$ python3 script.py 
Enter your move: ['rock', 'paper', 'scissors'], or "quit": 
paper
(<GameOption.paper: 1>, 'vs', <GameOption.scissors: 2>)
Enter your move: ['rock', 'paper', 'scissors'], or "quit": 
paper
(<GameOption.paper: 1>, 'vs', <GameOption.paper: 1>)
Enter your move: ['rock', 'paper', 'scissors'], or "quit": 
rock
(<GameOption.rock: 0>, 'vs', <GameOption.scissors: 2>)
Enter your move: ['rock', 'paper', 'scissors'], or "quit": 
scissors
(<GameOption.scissors: 2>, 'vs', <GameOption.rock: 0>)
Enter your move: ['rock', 'paper', 'scissors'], or "quit": 
rock
(<GameOption.rock: 0>, 'vs', <GameOption.paper: 1>)
Enter your move: ['rock', 'paper', 'scissors'], or "quit": 
quit

您可以使用字典将其转换为对应的整数。

guess = input("Enter your move: "rock", "paper", "scissors", or "quit": n")
guesses = {'rock':0, 'paper':1, 'scissors':2}
weapon = random.randint(0, 2)
output = (guesses[guess], weapon)

你不需要改变武器的类型,因为它已经是一个整数。

相关内容

  • 没有找到相关文章

最新更新