基本操作

1 赋值,+, *, len, in

 

# 赋值

tuple01 = (11, 22, 33, 44)

tuple02 = tuple01

print(tuple01)

print(tuple02)

 

# + 用来拼接元组

tuple01 = (11, 22, 33, 44)

tuple02 = (55, 66)

tuple03 = tuple01 + tuple02

print(tuple03)

 

# * 打印多少遍

tuple02 = (55, 66)

print(tuple02 * 3)

 

# len 求元组的元素个数

tuple01 = (11, 22, 33, 44)

print(len(tuple01))

 

# in 判断是否包含元素

tuple01 = (11, 22, 33, 44)

print("是否包含33", (33 in tuple01))

 

 

 2 添加元素 ,不支持:append,insert,extend

例:修改元素中的list列表

tuple01 = (11, 22, 33, [44, 55, 66])

tuple01[3].append(77)

tuple01[3].remove(55)

tuple01[3][2]=666

print(tuple01)

 

 3 删除元素 ,不支持:remove,pop,del,clear

tuple01 = (11, 22, 33, 44)

# del tuple01[2] 不可以修改元素

del tuple01  # 可以删掉整个元组,删掉后元组不能被访问调用

print(tuple01)

 

4计算,max,min,sum

tuple01 = (11, 22, 999, 33, 44)

print(max(tuple01))

print(min(tuple01))

print(sum(tuple01)) # 注意如果元组里面不是全是数值是无法求和的

 

 

5排序和反转,不支持:sort(),reverse(),支持:sorted()

tuple01 = (11, -10, 22, 999, 33, 44)

print(sorted(tuple01)) # 不改变元组中元素的位置,只是临时排序,是可以的

 

6查找,index

tuple01 = (11, -10, 22, 999, 33, 22, 44, 1001, 22)

print(tuple01.index(22))

print(tuple01.index(22,6)) # 从第六个元素开始查找22

 

7统计出现的次数 count

tuple01 = (11, -10, 22, 999, 33, 22, 44, 1001, 22)

print(tuple01.count(22))

 

 

执行结果:

C:\python\python.exe C:/python/demo/file3.py

(11, 22, 33, 44)

(11, 22, 33, 44)

(11, 22, 33, 44, 55, 66)

(55, 66, 55, 66, 55, 66)

4

是否包含33 True

(11, 22, 33, [44, 66, 666])

999

11

1109

[-10, 11, 22, 33, 44, 999]

2

8

3

 

Process finished with exit code 0