元组可以看成是一个不可更改的list
In [32]:
t = ()
print(type(t))
t = (1,)
print(type(t))
print(t)
t = 1,
print(type(t))
print(t)
t = (1,2,3,4,5)
print(type(t))
print(t)
t = 1,2,3,4,5
print(type(t))
print(t)
l = [1,2,3,4,5]
t = tuple(l)
print(type(t))
print(t)
(1,)
(1,)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)
元组的特性
是序列表,有序
元组数据值可以访问,不能修改,不能修改,不能修改
元组数据可以是任意类型
总之,list所有特性,除了可修改外,元组都具有
也就意味着,list具有的一些操作,比如索引,分片,序列相加,相乘,成员资格操作等,一模一样
In [33]:
t = (1,2,3,4,5)
print(t[4])
5
In [34]:
IndexError Traceback (most recent call last)
in ()
----> 1 print(t[12])
IndexError: tuple index out of range
In [37]:
t = (1,2,3,4,5,6)
t1 = t[1::2]
print(id(t))
print(id(t1))
print(t1)
t2 = t[2:100]
print(t2)
140249409775272
140249408604272
(2, 4, 6)
(3, 4, 5, 6)
In [46]:
t1 = (1,2,3)
t2 = (5,6,7)
print(t1)
print(id(t1))
t1 = t1 + t2
print(t1)
print(id(t1))
t1 = (1,2,3)
t1 = (2,3,4)
TypeError Traceback (most recent call last)
in ()
16 # tuple 的不可修改,指的是内容的不可修改
17 # 修改tuple内容会导致报错
—> 18 t1[1] = 100
TypeError: ‘tuple’ object does not support item assignment
In [48]:
t = (1,2,3)
t = t * 3
print(t)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
In [50]:
t = (1,2,3)
if 2 in t:
print(“YES”)
else:
print(“NO”)
YES
In [54]:
t = (1,2,3,“wangxiaojing”, “i”, “love”)
for i in t:
print(i, end=" ")
1 2 3 wangxiaojing i love
In [56]:
t = ((1,2,3), (2,3,4),(“i”, “love”, “wangxiaojing”))
for i in t:
print(i)
for k,m,n in t:
print(k,’–’,m,’–’,n)
(1, 2, 3)
(2, 3, 4)
(‘i’, ‘love’, ‘wangxiaojing’)
1 – 2 – 3
2 – 3 – 4
i – love – wangxiaojing
关于元组的函数
以下看代码
以下函数,对list基本适用
In [5]:
t = (1,2,3,4,5)
len(t)
Out[5]:
5
In [7]:
print(max(t))
print(min(t))
5
1
In [12]:
l = [1,2,3,4,5]
t = tuple(l)
print(t)
t = tuple()
print(t)
(1, 2, 3, 4, 5)
()
元组的函数
基本跟list通用
In [16]:
t = (2,1,2,3,45,1,1,2,)
print(t.count(2))
print(t.index(45))
print(t.index(1))
3
4
1
元组变量交换法
两个变量交换值
In [20]:
a = 1
b = 3
print(a)
print(b)
print("*" * 20)
c = a
a = b
b = c
print(a)
print(b)
print("*" * 20)
a,b = b,a
print(a)
print(b)
1
3
3
1
1
3