Python编写石头剪刀布游戏时报错generator与str无法相加如何解决
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)
相关疑问
不清楚报错中的generator对象是什么,搜索结果显示是通过循环生成的序列,但代码中仅用到while循环,并未编写生成器相关逻辑,不确定是否是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 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
可行解决方案
- 方案一:使用for循环配合数组索引简化实现
items = ['rock', 'paper', 'scissors'] for word in items: if items.index(word) == randomize - 1: print('Computer played: ', word)
- 方案二:使用enumerate函数优化原生成器表达式
原错误生成器写法:
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列表没有自带的显式索引匹配逻辑,需要自行实现对应功能,上述两种方案均可正常运行。
内容的提问来源于stack exchange,提问作者Marko Kolaksazov
相关产品推荐
相关产品推荐

