0%
Skip to content

元组

概念

有序不可变 的序列,就是不可变的列表

增删改只能新建,查找效率高于list

创建

python
# 标准创建
my_tuple1 = (1, 2, 3, 'a', 'b')

# 逗号是必须的,否则会被解释为整数 1
single_element_tuple = (1,) 

# tuple() 构造函数 (可以转换列表、字符串等可迭代对象)
list_data = [1, 2, 3]
string_data = "hello"

tuple_from_list = tuple(list_data)
tuple_from_string = tuple(string_data)

print(f"从列表转换: {tuple_from_list}")  # 从列表转换: (1, 2, 3)
print(f"从字符串转换: {tuple_from_string}")  # 从字符串转换: ('h', 'e', 'l', 'l', 'o')

其他

参考list