Tuple
元组和列表很类似,不同之处在于元组不能修改
元组使用 ( ) 、列表使用 [ ]
元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当做运算符使用
注:如果你读过我的上一篇博客 Python3 List , 想必你对序列类型的基本用法有了一定了解,因此,我不想对元组进行过多讲解,直接上例子。
1. 索引
>>> my_tuple = ("hello", "python", 2020)
print(my_tuple[1])
>>> my_tuple = ("hello", "python", 2020)
>>> print(my_tuple[:-1])
>>> print(my_tuple[1:2])
>>> print(my_tuple[:])
('hello', 'python')
('python',)
('hello', 'python', 2020)
2. 元组脚本操作符
>>> my_tuple = ("hello", "python", 2020)
print(len(my_tuple))
>>> tuple1 = (1, 2, 3)
>>> tuple2 = (4,)
>>> print(tuple1 + tuple2)
(1, 2, 3, 4)
>>> tuple1 = (1, 2, 3)
>>> print(tuple1 * 2)
(1, 2, 3, 1, 2, 3)
>>> tuple1 = (1, 2, 3)
>>> print( 1 in tuple1)
True
>>> tuple1 = (1, 2, 3)
>>> for t in tuple1:
>>> print(t, end=" ")
1 2 3
3. 元组内置函数
(1)len 函数,上面已经给出例子,此处不再重复
(2)max、min 函数:
>>> tuple1 = (1, 2, 3)
>>> print(max(tuple1))
>>> print(min(tuple1))
3
1
(3)tuple 函数,将可迭代系列转换为元组。
>>> list1 = [1, 2, 3]
>>> tuple1 = tuple(list1)
>>> print(tuple1)
(1, 2, 3)