Python构建游戏棋盘的字典嵌套列表时为何触发TypeError?
问题解决:嵌套列表的语法错误
你的代码报错是因为嵌套列表的子列表之间缺少逗号分隔。Python会把连续的两个列表[type1, type2, type1][type1, type3, type1]解析成「尝试用元组(type1, type3, type1)作为索引去访问第一个列表」,但列表索引只能是整数或切片,所以触发了TypeError。
修正后的代码只需在每个子列表末尾添加逗号:
type1 = {"Contents": "", "Type": "A"} type2 = {"Contents": "", "Type": "B"} type3 = {"Contents": "", "Type": "C"} board = [ [type1, type2, type1], [type1, type3, type1], [type3, type2, type1] ] return board
记住:Python列表中不管元素是单行还是多行排列,元素之间必须用逗号分隔,这是语法要求。
内容的提问来源于stack exchange,提问作者Brian Johnson
相关产品推荐
相关产品推荐

