Python新手:获取TypeError:不可用类型:' list'

时间:2016-12-14 06:15:25

标签: python arrays

所以我有一个班级作业,我必须做一个石头剪刀游戏,并停止作弊。我一直得到TypeError:unhashable类型:' 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]")

3 个答案:

答案 0 :(得分:2)

我注意到你的代码逻辑有些错误。

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

的内容
if element in list:
    # Do something

接下来,如果用户进行有效输入,则永远不会满足len(userThrow) > 1。因此,请len(userThrow) >= 1甚至== 1

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

最后,这是工作代码!

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

希望这有帮助! :)

答案 1 :(得分:0)

应该更正为

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()

    userThrow = raw_input("Enter Rock [r] Paper [p] or Scissors [s]") # raw_input() returns a string, and input() tries to run the input as a Python expression (assumed as python 2)

答案 2 :(得分:0)

您可以像这样实现:

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