1.元组是有序的,一般写元素的时候,推荐在最后加入逗号(,);
2.元组是可以迭代的;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,33)
for item in tuple_test:
print(item)
"""返回的结果
10
20
30
['list', 'Jim', 'Mary', (123, 'xuhongmei')]
True
33
"""
3.元组的一级元素是不能被修改的,如果元组中嵌套的二级元素是列表,是可以被更改的;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,33)
tuple_test[3][3]="yx"
print(tuple_test)
"""返回的结果
(10, 20, 30, ['list', 'Jim', 'Mary', 'yx'], True, 33)
"""
4.元组在一级元素不能增加元素,如果元组中嵌套的二级元素是列表,是可以增加元素的;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,33)
tuple_test[3].append("yuxianming")
print(tuple_test)
"""返回的结果
(10, 20, 30, ['list', 'Jim', 'Mary', (123, 'xuhongmei'), 'yuxianming'], True, 33)
"""
5.元组不能删除;
del tuple_test[0]
print(tuple_test)
"""返回结果报错
NameError: name 'tuple_test' is not defined
"""
6.元组可以查询;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,33)
v=tuple_test[3][3]
print(v)
"""返回的结果
(123, 'xuhongmei')
"""
7.元组可以切片查询;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,33)
v1=tuple_test[1:3]
print(v1)
"""返回的结果
(20, 30)
"""
8.元组、列表、字符串之间相互转换;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,33)
8.1 元组转换成列表;
v2=list(tuple_test)
print(v2)
"""返回的结果
[10, 20, 30, ['list', 'Jim', 'Mary', (123, 'xuhongmei')], True, 33]
"""
8.2元组转换成字符串,如果元组中含有数字,就不能使用join来转换,如果都是字符串则可以用join来转换;
str_test=""
for item in tuple_test:
item=str(item)
str_test=str_test+item
print(str_test)
"""返回的结果
102030['list', 'Jim', 'Mary', (123, 'xuhongmei')]True33
"""
9.count 获取指定元素在元组出现的次数;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,33,33,20,10)
v3=tuple_test.count(10)
print(v3)
"""返回的结果
2
"""
10. index 用于从元组中找出某个值第一个匹配项的索引位置;
tuple_test=(10,20,30,["list","Jim","Mary",(123,"xuhongmei")],True,10,33,20,10)
v4=tuple_test.index(10,2,8) 从下标2位置开始一直到8,第1个出现"10"的索引位置是5
print(v4)
"""返回结果
5
"""