python基础 - 09 容器类型 - 元祖

元祖: tuple ( )

Python 中的元组与列表类似,不同之处在于元组的元素不能修改。

1.定义元祖

tuple1 = ()     #定义一个空元祖
tuple2 = ('hanbo', 'wangyan', 100, 999);   #可以存不同类型的数据类型
tuple3 = (100)       #不加逗号就是int型
tuple4 = (100,)       #加逗号就是tuple型
tuple5 = "a", "b", "c", "d";   #  不需要括号也可以

2.使用元祖中的元素

(1) 使用索引(下标)去获取列表中的元素, 下标值可以取正负整数

#例如
tuple6 = (90, 99, 54, 76, 50, 34, 60, 88)
print(tuple6[0])    >>>90
print(tuple6[1])    >>>99
print(tuple6[7])    >>>88
print(tuple6[8])  # 注意:下标值不能超出范围,超出范围结果会报错.

print(tuple6[-1])    >>>88
print(tuple6[-5])    >>>76
print(tuple6[-7])    >>>99
print(tuple6[-10])  # 注意:使用负数同样不能越界

print(tuple6[1:3])  #截取元素 >>>99, 54

(2) 通过for循环遍历元祖

grades = (90, 99, 54, 76, 50, 34, 60, 88)
for i in range(0, len(grades)):      # 通过for循环取下标值
    print(grades[i])    #获取每一个元素值

3.元组中的元素值是不允许修改的,但我们可以对元组进行连接组合

tuple7 = (1, 2, 3)
tuple8 = (4, 5, 6)
print(tuple7 + tuple8)

4.元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组

tup = ('hanbo', 'wangyan', 1997, 2000)
print (tup)
del tup;
print ("删除后的元组 tup : ")
print (tup)

以上实例元组被删除后,输出变量会有异常信息,输出如下所示:
删除后的元组 tup :
  #会报错
NameError: name 'tup' is not defined

5.使用 tuple( ):将列表转换成元祖

list1= ['hanbo', 'wangyan']
tuple1=tuple(list1)
print(tuple1)
#输出结果:('hanbo', 'wangyan')

猜你喜欢

转载自blog.csdn.net/hanbo6/article/details/80325558