var = (1, 2, 3)
var = ("1", "2", "3")
var = (True, False)
var = (1.1, 1.11, 1.111)
var = ((1,), (2, 3), (4, 5))
var = ([1, 2], {"name": "polo"})
元组与列表很相似,都是有序的只读序列,两者有相同的方法和操作运算,区别在于:
lis = [1, 2, 3]
lis[0] = 111
print(lis)
tupl = (1, 2, 3)
tupl[0] = 2
# 输出结果
Traceback (most recent call last):
File "/Users/polo/Documents/pylearn/第一章:python 基本类型/6_tuple元组.py", line 21, in <module>
tupl[0] = 2
TypeError: 'tuple' object does not support item assignment
列表是可变对象,而元组是不可变对象,具体详解可以参考
https://cloud.tencent.com/developer/article/1857003
如果一个元组没有包含任何元素,使用 () 表示一个空元组
# 空
tup = ()
print(tup, type(tup))
# 输出结果
() <class 'tuple'>
如果一个元组只包含一个元素,要怎么表示?
# 只包含一个元素
tup = (1)
print(tup, type(tup))
# 输出结果
1 <class 'int'>
哎!竟然是 1,好像是哦,( ) 就是数学运算常见的括号呀,那到底要怎么表示呢
# 正确
tup = (1,)
print(tup, type(tup))
# 输出结果
(1,) <class 'tuple'>
需要在元素后加一个逗号,使用 (item, ) 表示该元组
当元组在 = 右边的时候,可以省略括号
# 等价写法
a = 1, 2
print(a, type(a))
a = (3, 4)
print(a, type(a))
a = 1,
print(a, type(a))
a = (3,)
print(a, type(a))
# 输出结果
(1, 2) <class 'tuple'>
(3, 4) <class 'tuple'>
(1,) <class 'tuple'>
(3,) <class 'tuple'>
# 索引
tup = [1, 2, 3, 4, 5]
print(tup[0])
print(tup[-1])
print(tup[2])
# 输出结果
1
5
3
# 切片
tup = [1, 2, 3, 4, 5, 6, 7, 8]
print(tup[:]) # 取全部元素
print(tup[0:]) # 取全部元素
print(tup[2:5]) # 取第 3 个元素到第 5 个元素
print(tup[::-1]) # 倒序取所有元素
print(tup[-3:-1]) # 取倒数第 3 个元素到倒数第 2 个元素
# 输出结果
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[3, 4, 5]
[8, 7, 6, 5, 4, 3, 2, 1]
[6, 7]
使用运算符 + 连接多个元组
# +
tup1 = (1,)
tup2 = (2, 3)
print(tup1 + tup2)
# 输出结果
(1, 2, 3)
使用运算符 * 将元组的元素重复
# *
tup = (1, 2)
print(tup * 2)
# 输出结果
(1, 2, 1, 2)
# in
tup = (1, 2, 3)
print(1 in tup)
print(22 not in tup)
# 输出结果
True
True
# len
tup = (1, 2, 3)
print(len(tup))
# 输出结果
3
# max
tup = (1, 2, 3)
print(max(tup))
# 输出结果
3
# min
tup = (1, 2, 3)
print(min(tup))
# 输出结果
1
元组与列表很相似,两者都表示一个有序的序列,它们的区别在于:
这点在可变对象、不可变对象文章都写了
# index
tup = (1, 2, 3)
print(tup.index(1))
print(tup.index(11))
# 输出结果
0
Traceback (most recent call last):
File "/Users/Documents/pylearn/第一章:python 基本类型/6_tuple元组.py", line 88, in <module>
print(tup.index(11))
ValueError: tuple.index(x): x not in tuple
返回元素 value 在元组中出现的次数
# count
tup = (1, 2, 1)
print(tup.count(1))
print(tup.count(11))
# 输出结果
2
0
因为元组是不可变对象,所以元组一般适合用来存储不变的数据