创建元组:
第一种方式:
>>> t1 = (11,22,33)
>>> type(t1)
<class 'tuple'>
第二种方式:
>>> t1 = tuple((11,22,33))
>>> type(t1)
<class 'tuple'>
索引及切片:
说明:索引及切片在元组里同样适用,但切片返回的是一个元组。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
t1 = (11,22,33,44)
# 索引
print(t1[1])
# 切片
print(t1[1:len(t1)-1])
运行结果:
元组(tuple)内部方法介绍:
count(self, value):
说明:统计某个元素在元组里出现的次数, value
表示即将统计的元素。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
t1 = (11,22,33,22,44)
# 统计 "22" 在元组中出现的次数
t2 = t1.count(22)
print(t2)
运行结果:
index(self, value, start=None, stop=None):
说明:在元组中查找指定元素的位置,如果存在返回指定元素的索引值,否则报错, value
表示指定的元素,start
表示开始的位置, end
表示结束的位置。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
t1 = (11,22,33,22,44)
# 查找 "22" 在元组中的位置
t2 = t1.index(22)
print(t2)
# 指定范围查找
t3 = t1.index(22,2,4)
print(t3)
运行结果:
将其他数据类型转换成元组:
def __init__(self, seq=()): # known special case of list.__init__
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
# (copied from class doc)
"""
pass
说明: tuple
接受的参数为可迭代的对象时,会将其转换成元组。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
l1 = [11,22,33]
print(type(l1))
# 将 列表 转换成 元组
t1 = tuple(l1)
print(type(t1))
运行结果:
元组嵌套修改:
元组的元素是不可修改的,但是元组的元素是列表或字典的话,其内部可以进行修改,即元组的元素的元素是有可以被修改的。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
t1 = (11,22,[33,{"k1":44}])
print(t1)
# 找到列表,在列表末尾追加 "66"
t1[2].append(66)
print(t1)
# 找到字典,将字典中键 "k1" 的值修改成 "55"
t1[2][1]["k1"] = 55
print(t1)
# 找到字典,添加内容
t1[2][1]["k2"] = 123
print(t1)
运行结果: