我试图通过在线课程学习在shell(jupyter notebook)/(anaconda提示符)中使用python中的元组。我被困在元组部分

问题描述 投票:-3回答:1

我的老师说元组是列表类型,它是不可变的。但我试过代码

>>>tuple1=[3,4,5,6]
>>>tuple1[1]=44
>>>tuple1
[3,44,5,6]



>>>list[3]=66

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 TypeError: 'type' object does not support item assignment

>>> s=['hi','hello',33]
>>> list[1]='hitech'
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'type' object does not support item assignment

这是输出。但我不知道为什么它没有显示

 <Error>
python tuples anaconda jupyter-notebook immutability
1个回答
1
投票

你的教师对于一个不可变的元组是正确的,但你的“元组”实际上是一个列表(带方括号)。

>>> tuple1 = [3, 4, 5, 6]
>>> type(tuple1)
<class 'list'>
>>> tuple1 = (3, 4, 5, 6)
>>> type(tuple1)
<class 'tuple'>
>>> tuple1[1] = 44
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

另一个问题是你试图从内置的list获取一个项目而不是一个真正的列表。

>>> my_list = [1, 2, 3, 4]
>>> my_list[3] = 66
>>> my_list
[1, 2, 3, 66]
>>> type(list)
<class 'type'>
>>> list[3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'type' object is not subscriptable
© www.soinside.com 2019 - 2024. All rights reserved.