首页 > 解决方案 > 为什么一个变量(随机数)的行为就像一个“发电机”

问题描述

我正在尝试在 python 上制作一个简单的石头剪刀布游戏

TypeError: unsupported operand type(s) for +: 'generator' and 'str'

这是我在代码中放置随机器后给出的错误消息:

Traceback (most recent call last)

<ipython-input-4-dea4c40cfdcd> in <module>()
 49   if key == 'q':
 50     break
---> 51   player_score, comp_score = gameplay(player_score, comp_score)
 52   print('Score is: YOU ', player_score, ' - ', comp_score, ' COMPUTER')
 53   print('')

 <ipython-input-4-dea4c40cfdcd> in gameplay(player_score, comp_score)
 12 
 13   comp_move = moves[randomize]
 ---> 14   battle = key + '-' + comp_move
 15 
 16   comp_print = (word for position, word in ['rock', 'paper', 'scissors'] if position == randomize - 1)

这个“生成器”对象是什么?在谷歌中,他们说它是使用循环制作的,所以它是一种序列,但不是用循环而不是while循环生成的。这个循环是错误的原因吗?此外,我没有使用字母序列,而只是其中的一个字母,我用它在序列中的位置编号来调用它?

这是错误之前的代码:

 from random import randint

 player_score = 0
 comp_score = 0
 key = None

 # Setting the rules
 choices = {'r-s': 'rock breaks scissors', 'p-r': 'paper envelopes rock', 's-p': 'scissors cut paper'}
 moves = {1: 'r', 2: 'p', 3: 's'}

 def gameplay(player_score, comp_score):

   comp_move = moves[randomize]
   battle = key + '-' + comp_move

以下是有关代码的更多详细信息:随机数在 while 循环内初始化

while True:
  randomize = randint(1, 3)
  print('<r>ock, <p>aper or <s>cissors? Press any key to continue; <q> for exit')
  key = check_input()
  if key == 'q':
    break
  player_score, comp_score = gameplay(player_score, comp_score)
  print('Score is: YOU ', player_score, ' - ', comp_score, ' COMPUTER')
  print('')
  key = None

但是,我在这里使用的是单个变量而不是变量序列,还是我错了?


就我在 Python 中查找数组的答案和解释而言,到目前为止,我已经找到了两种不同的方法来解决这个问题:

第一个是通过@John Coleman 的示例使用“for 循环”并使用数组索引简化表达式:

items = ['rock', 'paper', 'scissors']

  for word in items:
    if items.index(word) == randomize - 1:
      print('Computer played: ', word)

另一种方法是改善表达

item = (word for position, word in ['rock', 'paper', 'scissors'] if position == randomize - 1)

使用函数“枚举”:

  item = [word for position, word in enumerate(['rock', 'paper', 'scissors']) if position == randomize - 1]
  print('Computer played: ', item[0])

实际上,问题首先出现是由于Python中缺少数组的索引,因此您必须自己找出如何制作它们。

两种给定的解决方案都有效,因此可以认为该主题是“封闭的”。

标签: pythonarraysindexingtypeerrorgenerator

解决方案


check_input过于复杂,并且无意中返回了一个生成器对象(如果您尝试使用它,它还会引发错误)。

相反,只需执行以下操作:

def check_input():
  while True:
    inputed = input('Press a key: <r>, <p>, <s>, or <q>')
    if inputed  in ['p', 'q', 'r', 's']:
        return inputed
    print('Wrong input! Press a key: <r>, <p>, <s>, or <q>')

推荐阅读