"""
example04 - 初步学习Python
1.学习元组tuple
2.元组的应用
Author: danlis
Date: 2023/9/2
"""
START1 学习元组tuple
元组是不可变的容器*
str = (100) # 这实际上class 'int',所以如果需要构造一元组,必须后面加,str = (100,)
str1 = (100,)
print(type(str1))
重复运算------------------
字面量语法
str1 = ('hello', 'world', 'key', 'password')
print(str1 * 3) # 新的12元组,和str1没关系
print(str1)
成员运算------------------
print('key' in str1) # True
合并运算
str2 = ('my', 'name', 'is')
print(str1 + str2) # 新的元组
索引和切片--------------------------
结果password is ('hello', 'world') ('name', 'is'),注意切片type是tuple
print(str1[3], str2[-1], str1[:2], str2[1:])
隔一个取('world', 'password')
print(str1[1:4:2])
倒着一个一个取
print(str1[::-1])
元组不可以进行修改、删除---------------------
str1[3] = '赋值' # 会报错TypeError: 'tuple' object does not support item assignment
会报错TypeError: 'tuple' object doesn't support item deletion
del str1[0]
元组是没有对元素进行操作的函数,AttributeError: 'tuple' object has no attribute 'append'
str1.append('name')
删除元组是可以的
del str1
END1
START2 元组的应用
ValueError: too many values to unpack (无法解包) (expected 2) (要求2个)
右边括号中实际上就是一个三元组
a, b = (1, 2, 3)
元组的打包pack和解包unpack,将多的都打包到带*的变量中
a, b, *c = 5, 10, 15, 20, 25
a=5, b=10, c=[15, 20, 25]
print(f'a={a}, b={b}, c={c}')
_代替符号,当这个数不需要,可以用_代替
a, *_, c = 5, 10, 15, 20, 25
a=5, c=25
print(f'a={a}, c={c}')
a, *b, c = 5, 10, 15, 20, 25
print(f'a={a}, b={b}, c={c}')
*a, b, c = 5, 10, 15, 20, 25
print(f'a={a}, b={b}, c={c}')
两个值和三个值的时候,有单独对应的底层操作
ROT_TWO
a, b = b, a
ROT_THREE
a, b, c = b, c, a
4个以上进行打包解包操作
d = 0
a, b, c, d = b, c, d, a