Python基础-元组
1.定义及特点
元组是Python中最基本的数据结构,用()括起来。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。特点:有序 ,可重复,不可变
2.元组的基础操作
2.1元组的创建
th
=()
创建多元列表 th
=[123,1,'a','b',['i','www']]
强制转化 sr
='abcd'
th
=tuple(sr
)
2.2拼接
t1
=('a','b')
t2
=('c','d')
t
=t1
+t2
print(t
)
'('a
', 'b
', 'c
', 'd
')'
2.3重复
t
=('a', 'b', 'c', 'd')
print(t
*3)
'('a
', 'b
', 'c
', 'd
', 'a
', 'b
', 'c
', 'd
', 'a
', 'b
', 'c
', 'd
')'
2.4索引切片
t
=('a', 'b', 'c', 'd')
print(t
[::-1])
('d', 'c', 'b', 'a')
print(t
[2:])
('c', 'd')
print(t
[:2])
('a', 'b')
print(t
[1:3])
('b', 'c')
2.5查询元素
tp
= (1,2,3,1,['a','b','c'],1)
print(tp
[4].index
('a'))
print(tp
[0:3].index
(1))
'0'
'0'
2.6遍历
索引遍历
tp
= (1,2,3,'g',['a','b','c'],'d')
for i
in range(len(tp
))
print(tp
[i
])
元素遍历
tp
= (1,2,3,'g',['a','b','c'],'d')
for i
in tp
print(i
)
枚举遍历
tp
= (1,2,3,'g',['a','b','c'],'d')
for i
in enumerate(tp
,0):
print(i
)
转载请注明原文地址: https://win8.8miu.com/read-24276.html