对象不支持项目分配

对象不支持项目分配

本文介绍了类型错误:“元组"对象不支持项目分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简短的程序,它允许用户将数字列表输入到 input() 函数中,然后使用 add_25 函数将 25 添加到列表中的每个项目.

程序运行时出现以下错误:TypeError: 'tuple' object does not support item assignment

我尝试使用逗号分隔数字.这是程序:

testlist = [2,6,2]def add_25(mylist):对于范围内的 i (0, len(mylist)):mylist[i] = mylist[i] + 25返回我的列表打印 add_25(测试列表)actual_list = input("请输入一串数字,用逗号隔开:")打印 add_25(actual_list)
解决方案

在 Python 2 中 input() 将评估字符串,在这种情况下它将创建一个元组,因为元组是不可变的会得到那个错误.

>>>评估('1, 2, 3')(1, 2, 3)

使用更安全 raw_input 带有 list-comprehension 在这里:

inp = raw_input("请输入一串数字,用逗号隔开:")actual_list = [int(x) for x inp.split(',')]

或者,如果您不担心用户的输入,那么只需将元组传递给 list() 即可将元组转换为列表.

另请注意,当您尝试在函数内部就地更新列表时,返回列表是没有意义的,除非您想将另一个变量分配给同一个列表对象.要么返回一个新列表,要么什么都不返回.

I'm trying to write a short program which allows the user to input a list of numbers into an input() function, and then using the add_25 function add 25 to each item in a list.

I get the following error when the program runs: TypeError: 'tuple' object does not support item assignment

I tried dividing the numbers using a comma. This is the program:

testlist = [2,6,2]

def add_25(mylist):

    for i in range(0, len(mylist)):
        mylist[i] = mylist[i] + 25

    return mylist

print add_25(testlist)

actual_list = input("Please input a series of numbers, divided by a comma:")

print add_25(actual_list)
解决方案

In Python 2 input() will eval the string and in this case it will create a tuple, and as tuples are immutable you'll get that error.

>>> eval('1, 2, 3')
(1, 2, 3)

It is safer to use raw_input with a list-comprehension here:

inp = raw_input("Please input a series of numbers, divided by a comma:")
actual_list = [int(x) for x in inp.split(',')]

Or if you're not worried about user's input then simply convert the tuple to list by passing it to list().


Also note that as you're trying to update the list in-place inside of the function it makes no sense to return the list unless you want to assign another variable to the same list object. Either return a new list or don't return anything.

这篇关于类型错误:“元组"对象不支持项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 08:12