Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。

  1. >>> aTuple = ('et',77,99.9)
  2. >>> aTuple
  3. ('et',77,99.9)

元组也是一个容器类型,可以存储多个数据,只不过元组里面的数据不能修改,好比是一个只读的列表。
定义:(数据1,数据2,…)
元组的类型:tuple

<1>访问元组

  1. my_tuple=(1,3.14,'hello',[1,2,3],True)
  2. print(my_tuple,type(my_tuple)) #
  3. 错误的演示:
  4. my_tuple[0]=1 # 报错
  5. del my_tuple #报错
  6. 以上两个错误的演示,元组一旦定义完成,元组中的数据就不能修改。

python中有下标和切片,下标有正有负。正的从0开始,负的从-1开始。元组可以使用下标和切片。

  1. my_tuple[0]
  2. my_tuple[-1]
  3. my_tuple[1,-1]

元组中只有一个数据,那么元组中的逗号不能省略。

  1. my_tuple=('hello')
  2. print(my_tuple,type(my_tuple)) # str类型

元组的长度获取:len()

<2>元组不能删除和修改

说明: python中不允许修改元组的数据,包括不能删除其中的元素。

<3>count, index

index和count与字符串和列表中的用法相同

  1. >>> a = ('a', 'b', 'c', 'a', 'b')
  2. >>> a.index('a', 1, 3) # 注意是左闭右开区间
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. ValueError: tuple.index(x): x not in tuple
  6. >>> a.index('a', 1, 4)
  7. 3
  8. >>> a.count('b')
  9. 2
  10. >>> a.count('d')
  11. 0

<4>元组的应用场景

1、字符串格式化输出的时候,使用到了元组

  1. age=18
  2. name="wangyue"
  3. print("名字:%s, 年龄:%s" % (name,age)) #(name,age)就是元组

2、函数的返回值可以使用元组,这样外界可以使用函数的返回值,但是不能进行修改,更安全。

<4>元组的遍历

for循环遍历\while循环遍历

1、for循环遍历

  1. name_tuple=("张","王","李","赵")
  2. for name in name_tuple:
  3. print(name)

2、while循环遍历

  1. 获取元组的长度
  2. name_tuple=("张","王","李","赵")
  3. result=len(name_tuple)
  4. print("元组的长度",result)
  5. while index <len(name_tuple):
  6. value=name_tuple[index]
  7. print(value)
  8. index+=1

遍历字符串、元组、列表之类的最好都用for循环,因为写起来简单一些。