文章目录

  • 一、元组的定义语法
  • 1.基本语法
  • 2.元组的基本属性
  • 二、元组的基本操作
  • 1.使用下标访问元组中指定元素
  • 2.删除元组
  • 3.index()方法
  • 4.count()方法和len()方法
  • 三、元组的遍历循环
  • 1.while遍历元组
  • 2.for 遍历元组


一、元组的定义语法

1.基本语法

元组定义:定义元组使用小括号,且使用逗号隔开各个数据,数据可以是不同的数据类型。

# 定义元组字面量
(元素,元素,元素,.....,元素)
# 定义元组变量
变量名 = (元素,元素,元素,.....,元素)
# 定义空元组
变量名 = ()
变量名 = tuple()
t1 = ()
t3 = tuple()
t2 = (1,'hello',True)
print(f't1的类型是:{type(t1)},内容是:{t1}')
print(f't2的类型是:{type(t2)},内容是:{t2}')
print(f't3的类型是:{type(t3)},内容是:{t3}')

输出结果为:

t1的类型是:<class 'tuple'>,内容是:()
t2的类型是:<class 'tuple'>,内容是:(1, 'hello', True)
t3的类型是:<class 'tuple'>,内容是:()

2.元组的基本属性

  • 当定义的元组中只有一个元素时,在这个元素后要加上逗号,否则将不是元组类型的数据。
  • 元组内的元素是不可以修改的。
  • 元组可以容纳多种数据类型。
  • 元组内元素是有序存储的。
  • 元组内可允许重复元素存在。
  • 支持for和while遍历。

错误示范:

t1 = ('hello')
print(f't1的类型是:{type(t1)},内容是:{t1}')

输出结果为:

t1的类型是:<class 'str'>,内容是:hello  #输出结果为字符串

正确示范:

t1 = ('hello',)
print(f't1的类型是:{type(t1)},内容是:{t1}')

输出结果为:

t1的类型是:<class 'tuple'>,内容是:('hello',)  #输出结果委元组

二、元组的基本操作

1.使用下标访问元组中指定元素

t1 = (1,'hello',True)
print(t1[0])

输出结果为:

1

2.删除元组

使用del 元组名 进行对元组的删除。

3.index()方法

作用:查找指定元素下标。

t1 = (1,'hello',True)
x = t1.index('hello')
print(f'下标是{x}')

输出结果为:

下标是1

4.count()方法和len()方法

用法与列表相同

t1 = (1,'hello',True,'hello')
x = t1.count('hello')
s = len(t1)
print(f'数量是{x}')
print(f'长度是{s}')

输出结果为:

数量是2
长度是4

三、元组的遍历循环

1.while遍历元组

t1 = (1,'hello',True,'hello')
n = 0
while n < len(t1):
    x = t1[n]
    print(f'元组的元素有{x}')
    n += 1

输出结果为:

元组的元素有1
元组的元素有hello
元组的元素有True
元组的元素有hello

2.for 遍历元组

t1 = (1,'hello',True,'hello')
for i in t1:
    print(f'元组的元素有{i}')

输出结果为:

元组的元素有1
元组的元素有hello
元组的元素有True
元组的元素有hello