元组 和 列表 类似。最大的区别在于 元组不可变 而 列表可变
总结:元组最大的特点:不可变(元素不可被修改)
tup1 = ('a', 'a', 'b', 1, 2, 3)
print(type(tup1)) #
# 示例:有序、可重复
for i in tup1:
print(i, end=' ') # a a b 1 2 3
# 示例:不可变(不可被修改)
tup1[0] = 'x' # 报错
元组元素 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|
正向下标 | 0 | 1 | 2 | 3 | 4 |
反向下标 | -5 | -4 | -3 | -2 | -1 |
tup1 = (1, 2, 3, 4, 5)
print(tup1[0]) # 1
print(tup1[-1]) # 5
[start_index: end_index: step]
,其中参数描述如下:start_index:
起始索引(包含该索引本身),默认 0end_index:
终止索引(不包含该索引本身),默认一直取完数据step:
步长,默认 1。若为 正数,则表示正向下标,反之负向下标tup1 = (1, 2, 3, 4, 5)
print(tup1[0:4:1]) # (1, 2, 3, 4)
print(tup1[1::2]) # (2, 4)
print(tup1[::-1]) # (5, 4, 3, 2, 1)
tup1 = (1, 2, 3, 4, 5)
# 方式1:迭代
for i in tup1:
print(i, end=' ')
print()
print('------------------')
# 方式2:指定下标
print(tup1[0])
tup1 = ('a', 'b', 'c', 'd')
print(f'删除前:{tup1}')
del tup1
print(f'删除后:{tup1}')
# NameError: name 'tup1' is not defined
expr = (1, 2, 3) + (4, 5, 6)
print(f'组合元素:{expr}')
# 组合元素:(1, 2, 3, 4, 5, 6)
expr = ('Hi',) * 4
print(f'复制元素:{expr}')
# 复制元素:('Hi', 'Hi', 'Hi', 'Hi')
expr = 3 in (1, 2, 3)
print(f'判断元素是否存在:{expr}')
# 判断元素是否存在:True
tup1 = (1, 2, 3)
print(f'元组的个数是:{len(tup1)}')
# 元组的个数是:3
tup1 = (1, 2, 3)
tup2 = ('a', 'b', 'c')
print(f'tup1 的最大值是:{max(tup1)}') # 3
print(f'tup2 的最大值是:{max(tup2)}') # c
tup1 = (1, 2, 3)
tup2 = ('a', 'b', 'c')
print(f'tup1 的最大值是:{min(tup1)}') # 1
print(f'tup2 的最大值是:{min(tup2)}') # a
list1 = [1, 2, 3]
tup1 = tuple(list1)
print(tup1) # (1, 2, 3)
print(type(tup1)) #
tup1 = (1, 2, 3, 1, 1)
index1 = tup1.index(1)
print(f'第一次出现的索引:{index1}')
index1 = tup1.index(1, 1)
print(f'第一次出现的索引,下标从 1 开始算:{index1}')
tup1 = (1, 2, 3, 1, 1)
count1 = tup1.count(1)
print(f'元素出现的次数是:{count1}')