1. 课程目标
2. 创建元组
元组用圆括号,列表用方括号,
元组可以为空,空元组的布尔值为False
创建示例
>>> t = (1, 2, "hello", [1,2,3], True, ())
>>> type(t)
<class 'tuple'>
>>> ()
()
>>> tuple()
()
>>> bool(tuple())
False
>>>
元组中只有一个元素时,元素后面要加逗号
>>> tuple("python")
('p', 'y', 't', 'h', 'o', 'n')
>>> (3,)
(3,)
>>> type((3))
<class 'int'>
>>> type(("hello"))
<class 'str'>
>>> type(("hello",))
<class 'tuple'>
>>>
列表中加不加逗号都可以
>>> [1]
[1]
>>> [1,]
[1]
>>>
3. 元组的常用操作
3.1 元组的索引和切片
元组的索引、切片规则与列表一致
>>> t = (1, 3.14, "hello", [1,2,3], True, ())
>>> t[0]
1
>>> t[2]
'hello'
>>> t[::2]
(1, 'hello', True)
>>> t[1:]
(3.14, 'hello', [1, 2, 3], True, ())
>>> t
(1, 3.14, 'hello', [1, 2, 3], True, ())
>>>
3.2 元组的基本操作
元组的基本操作和列表一致,但元组的元素不能通过索引进行修改。
元组的元素不能修改,通过dir()查看到元组中没有修改元组的方法
>>> t
(1, 3.14, 314, [1, 2, 3], True, ())
>>> dir(t)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>>
通过“+”将多个元组的元素合并到一起,通过len()查看元组中元素的个数,通过in判断元素是否在元素中。
>>> t1 = (1, 2, 3)
>>> t2 = (2, 4, 5)
>>> t1 + t2
(1, 2, 3, 2, 4, 5)
>>> len(t1)
3
>>> 1 in t1
True
>>>
3.3 元组与列表之间的转换
元组中的元素的修改方式,通过将元组转化为列表进行修改,修改后的列表再转化为元组。
>>> t
(1, 3.14, 'hello', [1, 2, 3], True, ())
>>> tlst = list(t)
>>> tlst
[1, 3.14, 'hello', [1, 2, 3], True, ()]
>>> tlst[2] = 314
>>> tlst
[1, 3.14, 314, [1, 2, 3], True, ()]
>>> tuple(tlst)
(1, 3.14, 314, [1, 2, 3], True, ())
>>> t
(1, 3.14, 'hello', [1, 2, 3], True, ())
>>> t = tuple(tlst)
>>> t
(1, 3.14, 314, [1, 2, 3], True, ())
>>>
4. 元组的必要性
字典的键是不可修改的
5. 字符串、列表、元组的共同性
三者都是序列