Python入门教程4. 元组基本操作

前面简单介绍了Python列表基本操作,这里再来简单讲述一下Python元组相关操作

>>> dir(tuple) #查看元组的属性和方法
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> t1 = () #创建空元组
>>> tuple() #创建空元组
()
>>> (1,) #创建只有一个元素的元组(创建只有一个元素的元组,元素后面要有逗号,)
(1,)
>>> 1,
(1,)
>>> 2,3 #直接用逗号隔开两个值就可以创建一个元组
(2, 3)
>>> x,y = 2,3 #右边为一个元组
>>> x
2
>>> y
3
>>> x,y = y,x #使用元组复制,实现x与y交换值
>>> x
3
>>> y
2
>>> t2 = (1,2,3)
>>> t2[1] #获取序号为1的元组
2
>>> t2[1] = 4 #元组不能改变值,这里会报错!
Traceback (most recent call last):
 File "<pyshell#14>", line 1, in <module>
  t2[1] = 4
TypeError: 'tuple' object does not support item assignment
>>> t3 = (2,3,3,3,4,5)
>>> t3.count(3) # count()方法统计元组中元素3的个数
3
>>> t3.index(4) # index()方法获取元素4的位置序号
4

再次提醒注意:元组不能改变其值!!

简单入门教程~

基本一看就懂~O(∩_∩)O~

未完待续~~欢迎讨论!!