原文链接:http://www.juzicode.com/archives/3875
错误提示:
对set类型数据进行del操作时提示:TypeError: ‘tuple’ object doesn’t support item deletion
#juzicode.com/vx:桔子code
l = ['桔子','juzi','apple']
print(l)
del l[2]
print(l)
t = ('桔子','juzi','apple')
print(t)
del t[2]
print(t)
==========运行结果:
['桔子', 'juzi', 'apple']
['桔子', 'juzi']
('桔子', 'juzi', 'apple')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-ae6ecf1f848c> in <module>
6 t = ('桔子','juzi','apple')
7 print(t)
----> 8 del t[2]
9 print(t)
TypeError: 'tuple' object doesn't support item deletion
错误原因:
1、tuple类型的实例不可以进行元素的删除操作
解决方法:
1、可以通过先将tuple转换为list,删除list元素后再转换为tuple类型:
#juzicode.com/vx:桔子code
l = ['桔子','juzi','apple']
print(l)
del l[2]
print(l)
t = ('桔子','juzi','apple')
print(t)
lt = list(t) #tuple转换为list
del lt[2]
t = tuple(lt)
print(t)
['桔子', 'juzi', 'apple']
['桔子', 'juzi']
{'apple', 'juzi', '桔子'}
{'apple', 'juzi'}
扩展内容:
- Python基础教程2c–数据类型-list(列表)
- Python基础教程2d–数据类型-tuple(元组)
- Python基础教程2e–数据类型-dict(字典)
- Python基础教程2f–数据类型-set(集合)
关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识