python中的元组Tuple

一、创建元组

1、创建元组的格式: 元组名 = (元素1,元素2,……)

2、创建空的元组

tuple1 = ()

3、创建多个元素的元组

tuple2 = (1,2,3,"good","好")

4、创建只有一个元素的元组,括号中的逗号不能去掉,如果去掉,则变成了数字int类型的

tuple3 = (4,)
print(tuple3)
print(type(tuple3))

二、访问元组

1、访问元组中的元素:通过索引值访问,不能超过索引。也可以通过索引值为-1(访问最后一个元素)、-2(访问倒数第二个元素),以此类推。

tuple4 = (2,3,4,5,0)
print(tuple4[0])
print(tuple4[1])
print(tuple4[2])
print(tuple4[3])
print(tuple4[4])

2、不可修改元组中的元素

3、删除元组,删除后,不可再对元组进行操作

del tuple4

三、元组的操作

1、两个元组的元素拼接

tuple5 = (1,2,3)
tuple6 = (11,12,13)
print(tuple5 + tuple6) #(1,2,3,11,12,13)

2、元组重复

t7 = (1,2,3)
print(t7 * 3)  #(1, 2, 3, 1, 2, 3, 1, 2, 3)

3、元组的截取

t8 = (1,22,31,4,5,6,7,8,9)
print(t8[3:7])
print(t8[3:])
print(t8[:7])

四、元组的方法

1、求元组中元素的个数,len()

t9 = (1,2,3,4,5)
print(len(t9))

2、返回元组中元素的最大值、最小值:max(), min()

3、将列表转换成元组

list1 = [1,2,3]
t10 = tuple(list1)
print(t10)

猜你喜欢

转载自blog.csdn.net/zhang_cherry/article/details/81390032