[英]TypeError: 'tuple' object does not support item assignment when swapping values
I am writing a simple sort program in python and encounter this error.我正在 python 中编写一个简单的排序程序并遇到此错误。 I want to swap list elements but it returns an error.
我想交换列表元素,但它返回一个错误。 I am attaching the error and program in question below.
我在下面附上了有问题的错误和程序。
list[i+1] = list[i]
TypeError: 'tuple' object does not support item assignment
Code:代码:
def my_sort(list):
for index in range(1,len(list)):
value=list[index]
i=index-1
while i>=0:
if value<list[i]:
list[i+1] = list[i]
list[i]=value
i=i-1
else:
break
return
input_list=eval(input("Enter list items"))
my_sort(input_list)
print(input_list)
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
.评估 "1,2,3" 的结果是
(1, 2, 3)
,一个tuple
。 As you've discovered, tuples are immutable.正如您所发现的,元组是不可变的。 Convert to a list before processing.
处理前转换为列表。
or simply assign the whole tuple itself, instead of changing elements inside tuple.或者简单地分配整个元组本身,而不是更改元组内的元素。
example: want to add 'count' to 1st element of the 'i-th' tuple :示例:想要将 'count' 添加到 'i-th' 元组的第一个元素:
tup[i] = (tup[i][0] + count, tup[i][1])
To anyone googling this error: check for unwanted commas in your code.对于任何在谷歌上搜索此错误的人:检查代码中是否有不需要的逗号。 For example,
例如,
arr = np.zeros(n),
arr[i] = something
will throw this error.会抛出这个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.