本文共 1757 字,大约阅读时间需要 5 分钟。
在 Python 中,元组(tuple)是一种数据结构,用于存储多个元素。与列表(List)类似,但元组是不可变的,一旦创建就不能修改。元组中的元素可以是不同类型的数据,如整数、浮点数、字符串等。元组使用圆括号 () 定义,元素之间用逗号分隔。
x = ()print(x)
输出:()
x = (10, 20, 30, 40)print(x)print(x[1])print(x[1:5]) # 切片得到的是一个新元组
输出:
(10, 20, 30, 40)20(20, 30, 40)
x = (10)print(x)print(type(x))x = (10,)print(x)print(type(x))
输出:
10(10,)
x = 10, 20, 30, 40print(x)print(type(x))
输出:
(10, 20, 30, 40)
x = "hello", False, 10print(x)x = tupleprint(x)
输出:
('hello', False, 10) remove 方法x = (2596, "img")x.remove(2596) # 元组没有 `remove` 方法print(x)
输出:
(2596, "img")
pop 方法x = (2596, "img")x.pop() # 元组没有 `pop` 方法print(x)
输出:
(2596, "img")
del 可以删除整个元组x = (2596, "img")del x # 可以删除变量 `del x[0]` 也不可以删除元组中的元素print(x)
输出:
(2596, "img")
可见元组已经删除。
按照等号左边变量的顺序,依次把右边的值赋给左边的变量,左右结构必须一样。
x1, x2 = (10, 20)# 同时声明两个变量print(x1, x2)x1, x2 = [10, 20]# 列表也可以print(x1, x2)# 用元组取下标person = ("zhl", 21, "16609549548")print(person[0])name, age, phone = personprint(name, age, phone) 输出:
10 2010 20zhl 21 16609549548
少变量对应多变量可以使用 _ 来代替
n, img, _ = (256, "img", 200)print(img)# 使用下划线后n, img, _ = (256, "img", 200)print(img)
输出:
img
x1 = (10, 20)x2 = (30, 40)x3 = x1 + x2print(x3)
输出:
(10, 20, 30, 40)
x1 = (10, 20)x4 = x1 * 3print(x4)
输出:
(10, 20, 10, 20)
in 或 not inx = (10, 20, 10, 20, 10, 20)print(30 in x)print(30 not in x)
输出:
FalseTrue
x = (1, 2, 3, 4, 5)print(len(x)) # 长度print(max(x)) # 最大值print(min(x)) # 最小值print(sum(x)) # 求和print(x.index(3)) # 查找元素位置print(x.count(3)) # 统计元素个数
输出:
55151
通过本文,您可以掌握元组的基本知识及其常用操作,了解如何在 Python 中高效地使用元组进行数据存储和处理。
转载地址:http://doofk.baihongyu.com/