新的Python问题:获得TypeError:不可哈希类型:'list'

2024-09-29 01:38:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个课堂作业,我要做一个石头-布-剪刀的游戏,停止作弊。我一直在输入错误:不可损坏的类型:“list”

我不知道是什么原因造成的,有人能帮我解决这个问题吗?在

import random
import re

def MatchAssess(): 
    if userThrow == compThrow:
        print("Draw")
    elif userThrow == "r" and compThrow == "p":
        print("Computer chose paper; you chose rock - you lose")
    elif userThrow == "p" and compThrow == "s":
        print("Computer chose scissors; you chose paper - you lose!")
    elif userThrow == "r" and compThrow == "p":
        print("Computer chose paper; you chose rock - you lose!")
    elif userThrow == "s" and compThrow == "r":
        print("Computer chose rock; you chose scissors - you lose!")
    else:
        print("you win")



CompThrowSelection = ["r","p","s"]
ThrowRule = "[a-z]"

while True:
    compThrow = random.choice(CompThrowSelection)
    userThrow = input("Enter Rock [r] Paper [p] or Scissors [s]")
    if not re.match(CompThrowSelection,userThrow) and len(userThrow) > 1:
        MatchAssess()
    else:
        print("incorrect letter")
        userThrow = input("Enter Rock [r] Paper [p] or Scissors [s]")

Tags: andimportreyourandomcomputerpaperprint
3条回答

应更正为

if  userThrow in CompThrowSelection and len(userThrow) == 1: # this checks user's input value is present in your list CompThrowSelection and check the length of input is 1
    MatchAssess()

以及

^{pr2}$

您可以这样实现:

import random

cts = ["r","p","s"]

def match_assess(ut):
    ct = random.choice(cts)
    if ut == ct:
        print('Draw. You threw:'+ut+' and computer threw:'+ct)
    elif (ut=="r" and ct == "p") or (ut == "p" and ct == "s") or (ut == "r" and ct == "p") or (ut == "s" and ct == "r"):
        print ('You Loose. You threw:'+ut+' and computer threw:'+ct)
    else:
        print ('You Win. You threw:'+ut+' and computer threw:'+ct)
a = 0
while a<5: #Play the game 5 times.
    ut = raw_input("Enter Rock [r] Paper [p] or Scissors [s]")
    if ut in cts and len(ut) == 1:
        match_assess(ut)
    else:
        print("incorrect letter")
    a+=1

我注意到你的逻辑有点错误。在

一个是re.match()将应用于模式而不是列表上。对于list我们可以使用类似于

if element in list:
    # Do something

下一个问题是,如果用户输入了一个有效的输入,len(userThrow) > 1将永远不会得到满足。所以做len(userThrow) >= 1甚至{}。在

最后,我在条件分支上添加了一个continue语句,用于捕捉错误的输入,而不是从那里再次读取输入。在


最后,这是工作代码!在

^{pr2}$

希望这有帮助!:)

相关问题 更多 >