python入门笔记——元组
#元组元素不可修改,使用方法与列表类似
tuple1=(5,4,2,5)#只有一个元素时,也要加",",否则解释器不会当成元组来处理
# print(type(tuple1))
print(tuple1)
for item in tuple1:
print(item,end=' ')#for循环迭代输出tuple1中的元素
tuple2=('a','b','c',1,2,3)
print(tuple2)
print(tuple2[0])#输出元组tuple2中的第0号元素
print(tuple2[1:4:1])#输出元组tuple2中的第1到3号元素(左闭右开),步长为1(通常可省略)
print(tuple2[::-2])#倒序输出,并且步长为-2,故是隔两个取一个
print(tuple2[-2:-1:])
print(tuple2[-4:-2:])
#这里注意一下,这里前面两个用负值,即代表从右往左数,3是第-1位,2是-2位,以此类推
#且因为只有一个元素,所以输出的时候带有","
#取数的时候是正着取的,左闭右开
tuple3=()
print(id(tuple3))
tuple3=(1,2,3,4)
print(id(tuple3))
#虽然是两个相同名称的元组,但因为经过了重新初始化,填充了一些元素,故两者的地址是不一样的
tuple4=(1,2,3,2,['a','b','c'])
# tuple4[0]='python'
# TypeError: 'tuple' object does not support item assignment
# 元组中的数据是不能修改的,但例外是元组中有列表,可以修改列表中元素,如下:
tuple4[4][2]='Hello python'
print(tuple4)#将元组中的列表中的第2号元素,修改为了Hello python
print(tuple4.index(3))#和列表类似,查找某个元素的索引位置
print(tuple4.count(2))#统计某元素在该元组中出现次数
输出:
(5, 4, 2, 5)
5 4 2 5 ('a', 'b', 'c', 1, 2, 3)
a
('b', 'c', 1)
(3, 1, 'b')
(2,)
('c', 1)
1846757687368
1846759710376
(1, 2, 3, 2, ['a', 'b', 'Hello python'])
2
2
Process finished with exit code 0