python学习之【第五篇】:Python中的元组及其所具有的方法

1.前言

Python的元组(tuple)与列表很相似,不同之处在于元组不能被修改,即元组一旦创建,就不能向元组中的增加新元素,不能删除元素中的元素,更不能修改元组中元素。但是元组可以访问任意元素,可以切片,可以循环遍历,元组可以理解成是一个只读的列表。

2.元组的创建

元组创建很简单,元组使用小括号,只需要在括号中添加元素,并使用逗号隔开即可。

tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')
print(tup)
#输出
('hello', 'world', 'china', 'dog', 'cat')

3.访问元组中的元素

以索引方式访问

tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')
print(tup[0])
print(tup[1])
print(tup[2])
#输出
'hello'
'world'
'china'

以切片方式访问(包左不包右)

tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')
print(tup[0:3])    #打印索引从0到3的元素,不包含索引为3的元素
print(tup[1:])     #打印索引从1开始,一直到列表结束所有元素
print(tup[:-1])    #打印索引从0到倒数第2个元素之间的所有元素
#输出
('hello', 'world', 'china')
('world', 'china', 'dog', 'cat')
('hello', 'world', 'china', 'dog')

4.删除元组

tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')
del tup
print(tup)
#输出报错,因为元组已经被删除
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tup' is not defined

5.元组的遍历

tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')
for tt in tup:
    print(tt)
#输出
'hello'
'world'
'china'
'dog'
'cat'

猜你喜欢

转载自www.cnblogs.com/wangjiachen666/p/9610280.html