为什么变量(随机数)的行为像'generator'



我想做一个简单的石头剪刀布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)

函数'enumerate':

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

实际上,这个问题首先是由于Python中数组缺乏索引而出现的,因此你必须自己找出如何创建它们。

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

你的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>')

最新更新