我正在尝试使用此代码并使用此代码我收到此错误:
File "E:\Snacks.py", line 93, in runGame
obsCoords.insert(0, newobs)
AttributeError: 'dict' object has no attribute 'insert'
那是因为我在列表后面设置了一个位置:
obsCoords = []
obscoords = getRandomLocation()
if (event.key == K_q) and len(wormCoords) >= 4:
del wormCoords[-1]
obsCoords['x'] = wormBody['x']
obsCoords['y'] = wormBody['y']
newobs = {'x': obsCoords['x'], 'y': obsCoords['y']}
obsCoords.insert(0, newobs)
if wormCoords[HEAD]['x'] == obsCoords['x'] and wormCoords[HEAD]['y'] == obsCoords['y']:
return
所以我将其删除:
obsCoords = []
if (event.key == K_q) and len(wormCoords) >= 4:
del wormCoords[-1]
obsCoords['x'] = wormBody['x']
obsCoords['y'] = wormBody['y']
newobs = {'x': obsCoords['x'], 'y': obsCoords['y']}
obsCoords.insert(0, newobs)
if wormCoords[HEAD]['x'] == obsCoords['x'] and wormCoords[HEAD]['y'] == obsCoords['y']:
return
并最终出现此错误:
TypeError: list indices must be integers, not str
我想要做的就是在列表中添加新位置。有人可以帮我吗?
答案 0 :(得分:0)
在你的第一个代码中,你有两个错误:
obsCoords = []
obscoords = getRandomLocation()
第一个是您实际上声明两个看起来相似的不同变量。虽然我认为这是一个错字......这导致了我的第二个错误:
obsCoords = []
obsCoords = getRandomLocation()
在这里,您要创建一个列表obsCoords
,用getRandomLocation()
的结果覆盖obsCoords = []
…
newobs = {'x': obsCoords['x'], 'y': obsCoords['y']}
obsCoords.insert(0, newobs)
…
obsCoords['x']
,无论它是什么,这可能不是您想要的。< / p>
然后在你的第二段代码中,你正在做:
obsCoords
该代码完全没有意义!
您正在创建列表newobs
,然后通过像字典一样访问obsCoords
来创建x
,以获得y
和obsCoords
。然后你想在x
中插入它,就像它是一个列表一样,最后尝试从obsCoords
得到obsCoords = [] # obsCoords -> []
obsCoords['x'] # obsCoords is an empty list.
obsCoords['y'] # for this to work it should be : {'x': …, 'y': …}
# suppose it did not fail, here's what's next:
obsCoords.insert(0, newobs) # obsCoords -> [{'x': …, 'y': …}]
obsCoords['x'] # again you're accessing like a dict!
值,如dict:
obsCoords
你想要什么? {{1}}是列表还是字典?!