文章目录
书写格式
tup = (111,“alex”,(11,22),[(33,44),True,33,44],)
#一般元组推荐在最后加入’,’
1.元组的元素不可被修改,不能被增加或者删除
a.元组的一级元素不可修改,但是二级元素可以
tup[3][1] = 4
print(tup)
2.引索
v = tu[0]
print(v)
3.切片
v = tu[0:2]
print(v)
4.可以被for循环,即可迭代对象
for i in tu:
print(i)
5.转换(可更详细讨论几种数据类型同tuple类型之间的转换)
s = "asdjfpqaehrgj"
li= ["asdf","aoirjeiondda"]
tu= (li)#这样子不行,不能这样转换
print(tu)
print(type(tu))
#这样子可以list-->tuple
tu2 = tuple(li)
print(tu2)
print(type(tu2))
(‘asdf’, ‘aoirjeiondda’)
<class ‘tuple’>
#dict-->tuple, 只能将字典中的key变为tuple,貌似tuple迭代的时候是
#只将key作为迭代对象
dict_1 = {'a':123,'z':'465','b':65}
tu3 = tuple(dict_1)
print(tu3)
print(type(tu3))
(‘a’, ‘z’, ‘b’)
<class ‘tuple’>
6. .count()获取指定元素在元组一级元素中出现的次数
tu = (111,22,'asdfa',['asdfa'],{'a':'asdf'})
print(tu)
print(tu.count('asdfa'))
print(tu.count(22))
7.获取指定元素在元组一级元素中出现的index
tu = (111,22,'asdfa',['asdfa'],{'a':'asdf'})
print(tu.index(111))