元组可以包含任意数量的元素,并且每个元素可以是不同的数据类型。例如:
t2 = (None, False, "hello", [1, 2], ())
t1 = (1,)
t2 = (None, False, "hello", [1, 2], ())
t0 = (2, 3)
# t0[0] = 5
# TypeError: 'tuple' object does not support item assignment
t2 = (None, False, "hello", [1, 2], ())
t2[3].append(6)
print(t2[3])
print(t2)
# [1, 2, 6]
# (None, False, 'hello', [1, 2, 6], ())
for e in t2:
print(e)
for i in range(len(t2)):
print(t2[i])
t3 = (1, 2, 3, 5, 6, 1, 1, 2, 3)
print(t3.count(1))
# 3
print(t3.index(5))
# 3
设置条件,即存在某元素时才进行查找索引。
value = 9
if value in t3:
print(t3.index(value))
else:
print(f"{value}不在元组中")
# 9不在元组中
t1 = ("a", "b", "c")
print(id(t1), type(t1), t1)
t2 = (1, 2, 3)
t1 = t1 + t2
print(id(t1), type(t1), t1)
# 2407770816000 ('a', 'b', 'c')
# 2407770835648 ('a', 'b', 'c', 1, 2, 3)
构建不可变的键值对: 在Python中,可以使用元组构建不可变的键值对,然后将这些键值对放入字典中。由于元组是不可变的,可以保证键的唯一性和不变性。
my_dict = {('John', 25): 'Engineer', ('Alice', 30): 'Manager'}
my_tuple = (10, 20, 30)
a, b, c = my_tuple
print(a, b, c) # 输出:10 20 30