# Python中tuple的用法
# 创建一个空元组
empty_tuple = ()
print(empty_tuple) # 输出: ()
# 创建一个包含元素的元组
tuple_with_elements = (1, 2, 3, 'a', 'b', 'c')
print(tuple_with_elements) # 输出: (1, 2, 3, 'a', 'b', 'c')
# 元组可以包含不同类型的元素
mixed_tuple = (1, "hello", 3.14, True)
print(mixed_tuple) # 输出: (1, 'hello', 3.14, True)
# 访问元组中的元素
first_element = tuple_with_elements[0]
print(first_element) # 输出: 1
# 元组是不可变的,不能修改其中的元素
# 下面这行代码会抛出 TypeError: 'tuple' object does not support item assignment
# tuple_with_elements[0] = 10
# 可以使用切片访问多个元素
subset = tuple_with_elements[1:4]
print(subset) # 输出: (2, 3, 'a')
# 元组支持拼接
concatenated_tuple = tuple_with_elements + mixed_tuple
print(concatenated_tuple) # 输出: (1, 2, 3, 'a', 'b', 'c', 1, 'hello', 3.14, True)
# 元组可以解包
x, y, z, *rest = tuple_with_elements
print(x, y, z, rest) # 输出: 1 2 3 ['a', 'b', 'c']
# 使用 in 关键字检查元素是否存在
exists = 'a' in tuple_with_elements
print(exists) # 输出: True
# 获取元组的长度
length = len(tuple_with_elements)
print(length) # 输出: 6
上一篇:python 多行字符串
下一篇:python tempfile
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站