python——tuple元组

>>> dir(tuple)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> tuple
<type 'tuple'>
>>> tuple_1=(1,2,3,4,5,6)
>>> tuple_1
(1, 2, 3, 4, 5, 6)
>>> tuple[0]=1

Traceback (most recent call last):
  File "<pyshell#77>", line 1, in <module>
    tuple[0]=1
TypeError: 'type' object does not support item assignment
>>> 

tuple就是元组的类型,他和列表相近,但是也有很大的区别,如上,tuple不能修改元素,如果修改就会报错,如上

判断一个列表可以看中括号,但是看元组的依据主要是逗号

eg:如果我们只是需要一个元素,如果不加上逗号,那么会被默认为一个整数类型,如果在后面加上一个逗号,就会被认为是tuple

>>> tuple_2=(1)
>>> tuple_2
1
>>> type(tuple_2)
<type 'int'>
>>> tuple_3=(1,)
>>> tuple_3
(1,)
>>> type(tuple_3)
<type 'tuple'>
>>> 

但是对于空的加不加逗号就不影响了

>>> list1=[]
>>> type(list1)
<type 'list'>
>>> tuple1=()
>>> type(tuple1)
<type 'tuple'>
>>> 

因为元组不能更改,所有列表里面的3中添加和删除都不能使用

但是我们可以通过切片进行增加和删除

>>> 
>>> tmp1=(1,2,4,5,6)
>>> tmp1=tmp1(:2)
SyntaxError: invalid syntax
>>> tmp1=tmp1[:2]+tmp[3:]

Traceback (most recent call last):
  File "<pyshell#103>", line 1, in <module>
    tmp1=tmp1[:2]+tmp[3:]
NameError: name 'tmp' is not defined
>>> tmp1=tmp1[:2]+tmp1[3:]
>>> tmp1
(1, 2, 5, 6)
>>> tmp1=tmp1[:2]+(4,)  #这里注意加上的单个元素一定要加上逗号
>>> tmp1
(1, 2, 4)
>>> 
原文地址:https://www.cnblogs.com/13224ACMer/p/5918474.html