首页 > 技术文章 > 元组tuple

REN-Murphy 2020-11-02 13:29 原文

数据类型:int整型  float浮点数  bool布尔值  str字符串  list列表  tuple元组  dict字典  set集合

  可变数据类型:
    字典、列表、集合、自定义的对象等
  不可变数据类型:
    数字、字符串、元组、function等

tuple(不可变数据类型)

概念:
  Python 元组 tuple() 函数将列表转换为元组。

定义形式:
  tuple1 = ("王权富贵","东方月初")
元素的访问:
  通过索引值访问

注意:元组是不可变数据类型,即存储的元素的值,不可修改,不可删除
tuple_1 = ("王权富贵","东方月初","颜如玉")

# 访问第一个《狐妖小红娘》名字
print("第一个人的名字:",tuple_1[0])
# 第一个人的名字: 王权富贵

# 访问最后一个《狐妖小红娘》名字
print("最后一个人的名字:",tuple_1[-1])
# 最后一个人的名字: 颜如玉
print("最后一个人的名字:",tuple_1[len(tuple_1)-1])
# 最后一个人的名字: 颜如玉
遍历列表(while循环、for循环)
tuple_1 = ("王权富贵","东方月初","颜如玉")

# 如何打印元组中所有的数据(遍历)
# 1.使用 while循环
i = 0
print("使用while遍历元组中的元素:")
while i < len(tuple_1):
    print(tuple_1[i],end="\t")
    i += 1

# 2.使用第一种for循环
print("\n使用第一种for遍历元组中的元素:")
for i in range(len(tuple_1)):
    print(tuple_1[i],end="\t")

# 3.使用第二种for循环
print("\n使用第二种for遍历元组中的元素:")
for name in tuple_1:
    print(name,end="\t")

操作元组常用的方法

 由于元组本身,是不可变数据类型,因此增、删、改的操作都不能进行



AttributeError: 'tuple' object has no attribute 'append'
元组是不可变对象,不能实现插入功能

AttributeError: 'tuple' object has no attribute 'remove'
元组是不可变对象,不能实现删除功能

TypeError: 'tuple' object does not support item assignment
元组是不可变对象,不能实现修改功能

查(index、count、in、not in )
  index()
   查找指定元素的值,在列表中的索引值(如果有,返回索引值,没有则报错 ValueError)

  count()
  计算指定元素出现的次数(如果有,返回出现的次数,没有则返回0)

  in
   返回bool值,True/False

  not in
  返回bool值,True/False
tuple_1 = ("王权富贵","东方月初","颜如玉")

# ---------------查询操作-------------------
# index查找指定元素的值,在列表中的索引值
print("元组元素\"东方月初\"的索引值:",tuple_1.index("东方月初"))
# count计算指定元素出现的次数
print("元组元素\"东方月初\"出现的次数:",tuple_1.count("东方月初"))
# in 与 not in
print("元组元素\"东方月初\"是否在元组里面:","东方月初" in tuple_1)
print("元组元素\"东方月初\"是否不在元组里面:","东方月初" not in tuple_1)

转换:列表与元组相互转换

list <==> tuple
tuple元组是不可变对象,但是可以转换为list列表进行增删改查操作(list是可变对象)
tuple_1 = ("王权富贵","东方月初","颜如玉")

# 将元组和列表相互转换
list_1 = list(tuple_1)
print("list_1 = {0}\t 数据类型为:{1}".format(list_1, type(list_1)))
list_1.append("律笺文")
list_1.append("涂山古情巨树")
print("list_1 = {0}\t 数据类型为:{1}".format(list_1, type(list_1)))
tuple_1 = tuple(list_1)
print("tuple_1 = {0}\t 数据类型为:{1}".format(tuple_1,type(tuple_1)))


 
 

推荐阅读