元组
1.创建元组
>>> a=()
>>> type(a)
<class 'tuple'>
#可以将元组看作一个容器,任何数据类型都可以放在这个容器里面
>>> b=(1,1.2,1+1j,[3,4],{"a":"b"},"c")
>>> type(b)
<class 'tuple'>
#单个元组的定义,一定要在这个元素后面加上逗号
>>> c=(1,)
>>> type(c)
<class 'tuple'>
#定义单个元组时不加逗号的后果
>>> d=(1)
>>> type(d)
<class 'int'>
#判断对象是否为元组类型
>>> isinstance(c,tuple)
True
>>> isinstance(d,tuple)
False
#转换类型
>>> tuple([1,2])
(1, 2)
>>> tuple({1:2})
(1,)
>>> tuple({2:3,"a":"b"}) #注意,字典转换为元组类型时,只取字典中的key值放在元组里
(2, 'a')
2.操作元组
a.索引
>>> a=(1,1.2,1+1j,[3,4],{"a":"b"},"c")
>>> a[3]
[3, 4]
>>> a[-1]
'c'
b.切片
>>> a=(1,1.2,1+1j,[3,4],{"a":"b"},"c")
>>> a[1:]
(1.2, (1+1j), [3, 4], {'a': 'b'}, 'c')
>>> a[::-1]
('c', {'a': 'b'}, [3, 4], (1+1j), 1.2, 1)
>>> a[3:6]
([3, 4], {'a': 'b'}, 'c')
c.修改
*元组中的不可变对象不能被修改,否则异常;字典中的元素为列表或字典时是可以修改的
>>> a=(1,1.2,1+1j,[3,4],{"a":"b"},"c")
>>> a[0]=3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a[3].append(5)
>>> a
(1, 1.2, (1+1j), [3, 4, 5], {'a': 'b'}, 'c')
>>> a[4]["d"]="f"
>>> a
(1, 1.2, (1+1j), [3, 4, 5], {'a': 'b', 'd': 'f'}, 'c')
d.删除
*元组中的元素不可以删除,但是可以删除整个元组
>>> a=(1,1.2,1+1j,[3,4],{"a":"b"},"c")
>>> del a[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
>>> del a
e.循环
>>> a=(1,1.2,1+1j,[3,4],{"a":"b"},"c")
>>> for i in a:
... print (i)
...
1
1.2
(1+1j)
[3, 4, 5]
{'a': 'b', 'd': 'f'}
C
f.枚举
#输出元素索引位置及对应的元素
>>> a=(1,1.2,1+1j,[3,4],{"a":"b"},"c")
>>> for i,j in enumerate(a):
... print (i,j)
...
0 1
1 1.2
2 (1+1j)
3 [3, 4, 5]
4 {'a': 'b', 'd': 'f'}
5 c
g.运算符
#in和not in
>>> a=(1,2,3)
>>> 1 in a
True
>>> "a" in a
False
>>> "a" not in a
True
>>> 1 and 2 in a
True
#*乘法/set去重
>>> b=("a","b")
>>> b*5
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')
>>> tuple(set(b*5))
('a', 'b')
#+连接
>>> a=(1,2,3)
>>> b=("a","b","c")
>>> a+b
(1, 2, 3, 'a', 'b', 'c')
h.内置函数
>>> a=(1,2,3,4,4,5)
>>> min(a) #最小值
1
>>> max(a) #最大值
5
>>> len(a) #元组长度
6
>>> a.count(4) #元素4的个数
2
>>> a.index(3) #元素3的索引位置
2