Python 如何修复:TypeError 'tuple' 对象不支持项目分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19338209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:30:13  来源:igfitidea点击:

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

pythonpygame

提问by Pro-grammer

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

本教程中的以下代码片段: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 badguyis a tuple. This means it is immutable(you can not change its values) Ive tried the following:

我知道这可能是因为badguy是一个元组。这意味着它是不可变的(你不能改变它的值)我尝试了以下方法:

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.

我将元组转换为一个列表,这样我们就可以减去 7。但在游戏中什么也没有发生。

Does any one know what I could do?

有谁知道我能做什么?

Thanks.

谢谢。

采纳答案by inspectorG4dget

Change this

改变这个

badguy[0]-=7

into this

进入这个

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

Alternatively, if you can leave badguyas 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)

或者,如果您可以保留badguy为 a list,那么甚至不使用元组,您当前的代码就可以了(增​​加了使用列表而不是元组的更改)

回答by SethMMorton

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.

这与第零个元素中的更新值一起创建了一个新元组。

回答by SSR

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

你可以做一个 np.copy() 并与她一起工作。

badguy_copy = np.copy(badguy)