How to fix a : TypeError 'tuple' object does not support item assignment

醉酒当歌 提交于 2021-02-06 19:34:05

问题


The following fragment of code from this tutorial: http://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python

for badguy in badguys:
        if badguy[0]<-64:
            badguys.pop(index)
        badguy[0]-=7
        index+=1
    for badguy in badguys:
        screen.blit(badguyimg, badguy)

is giving me a :

TypeError: 'tuple' object does not support item assignment

I understand that this could be becuse badguy is a tuple. This means it is immutable(you can not change its values) Ive tried the following:

t= list(badguy)
        t[0]= t[0]-7
        i+=1

I converted the tuple to a list so we can minus 7. But in the game nothing happens.

Does any one know what I could do?

Thanks.


回答1:


Change this

badguy[0]-=7

into this

badguy = list(badguy)
badguy[0]-=7
badguy = tuple(badguy)

Alternatively, if you can leave badguy as a list, then don't even use tuples and you'll be fine with your current code (with the added change of using lists instead of tuples)




回答2:


Another solution is instead of

badguy[0] -= 7

to do

badguy = (badguy[0] - 7,) + badguy[1:]

This creates a new tuple altogether with the updated value in the zeroth element.




回答3:


You can do a np.copy() and work with her.

badguy_copy = np.copy(badguy)


来源:https://stackoverflow.com/questions/19338209/how-to-fix-a-typeerror-tuple-object-does-not-support-item-assignment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!