【问题标题】:Trying to set a variable from a value in a dictionary尝试从字典中的值设置变量
【发布时间】:2016-01-25 20:06:14
【问题描述】:

我正在学习 python,正在创建一个石头剪刀布游戏。

我被困在一个部分。

我目前有 4 个变量(虽然我想把它减少到 2 个)

  • pKey
  • pChoice
  • comKey
  • comChoice

他们分别在字典中查找 Key 和 Value。

choice = {1:'rock',  2:'paper',  3:'scissors'}

我遇到的问题是使用变量从字典中获取键。

这是给我带来麻烦的代码 sn-p

    print('--- 1 = Rock    2 = Paper     3 = Scissors --- ')
    pKey = input() # this is sets the key to the dictionary called choice
    while turn == 1: # this is the loop to make sure the player makes a valid choice
        if pKey == 1 or 2 or 3:
            pChoice = choice.values(pKey)  # this calls the value from choice dict and pKey variable
            break
        else:
            print('Please only user the numbers 1, 2 or 3 to choose')

    comKey = random.randint(1, 3)  # this sets the computer choices
    comChoice = choice.values(comKey)

具体麻烦的部分是

 pChoice = choice.values(pKey)

 comChoice = choice.values(comKey)

我已经尝试了我所知道的一切,包括使用括号、尝试不同的方法和使用不同的格式。

很想学这个!谢谢!

【问题讨论】:

  • 小心if pKey == 1 or 2 or 3。它没有做你认为的那样。
  • 谢谢,我会不顾一切地说,如果 pKey == 1 或 pKey == 2 或 pKey == 3,我需要它:是在正确的轨道?
  • 您可以使用if pKey == 1 or pKey == 2 or pKey == 3,也可以使用if pKey in [1, 2, 3]。然而现在这永远不会是真的,因为pKey"1""2""3"

标签: python dictionary setvalue


【解决方案1】:

听起来您只是在尝试查找字典

pKey = 1
pChoice = choices[pKey]  # rock

dict.values 用于创建包含字典所有值的列表(实际上是dict_values 对象)。它不用作查找。


就您的代码结构而言,它可能需要一些工作。摇滚/纸/剪刀选择非常适合Enum,但现在可能有点超出您的范围。让我们尝试作为顶级模块常量。

ROCK = "rock"
PAPER = "paper"
SCISSORS = "scissors"

def get_choice():
    """get_choice asks the user to choose rock, paper, or scissors and
    returns their selection (or None if the input is wrong).
    """
    selection = input("1. Rock\n2. Paper\n3. Scissors\n>> ")
    return {"1": ROCK, "2": PAPER, "3": SCISSORS}.get(selection)

将它们作为常量寻址可确保它们在您的代码中的任何地方都相同,否则您会得到一个非常清晰的 NameError(而不是因为您执行了 if comChoice == "scisors" 而导致 if 分支未执行)


带有枚举的最小示例如下所示:

from enum import Enum

Choices = Enum("Choices", "rock paper scissors")

def get_choice():
    selection = input(...)  # as above
    try:
        return Choices(int(selection))
    except ValueError:
        # user entered the wrong value
        return None

您可以通过使用更详细的 Enum 定义来扩展它,并教每个 Choice 实例如何计算获胜者:

class Choices(Enum):
    rock = ("paper", "scissors")
    paper = ("scissors", "rock")
    scissors = ("rock", "paper")

    def __init__(self, loses, beats):
        self._loses = loses
        self._beats = beats

    @property
    def loses(self):
        return self.__class__[self._loses]

    @property
    def beats(self):
        return self.__class__[self._beats]

    def wins_against(self, other):
        return {self: 0, self.beats: 1, self.loses: -1}[other]

s, p, r = Choices["scissors"], Choices["paper"], Choices["rock"]
s.wins_against(p)  # 1
s.wins_against(s)  # 0
s.wins_against(r)  # -1

不幸的是,没有什么好的方法可以消除其中的抽象(每次调用时都将“paper”抽象为 Choices.paper),因为当 Choices.rock 被实例化时,您不知道 Choices["paper"] 是什么。

【讨论】:

  • 我还没有看到我正在写的这本书的Enum 部分,但这看起来确实更干净,更容易阅读。我会查查的。感谢大家的帮助!
【解决方案2】:

您不知道如何从 dict 中获取元素,您的代码应该是这样的:

import random
choice = {1: 'rock',  2: 'paper',  3: 'scissors'}

print('1 = Rock\t2 = Paper\t3 = Scissors')
pKey = int(input())
if pKey in (1, 2, 3):
    pChoice = choice[pKey]
else:
    print('Please only user the numbers 1, 2 or 3 to choose')
    pChoice = 'No choice'

comKey = random.randint(1, 3)
comChoice = choice[comKey]
print(pChoice, comChoice)

对我来说很好。

【讨论】:

  • 请将if pkey == 1 or 2 or 3 更改为实际可用的名称,例如int(pkey) in [1,2,3]。目前,它将被读取为if (pkey == 1) or (2) or (3),它将始终断言为True
  • 谢谢!如果我可能会问,因为我是新手,为什么需要将其更改为 Int 才能工作? pChoice = choice[int(pKey)] 是否将 pKey 读取为字符串,即使它是一个数字?
  • @EddieFlores 是的,你总是从 input() 得到字符串
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
相关资源
最近更新 更多