Lesson 2#04 元组

元组,又称为只读列表

#小括号是元组( )
#中括号是列表[ ]
#大括号是字典{ }
names = ("suyp","lirs","liuzhen","machao")

特性:元组本身不可变,如果元组中包含其他可变元素,这些元素是可变改变的

names = ("suyp","lirs","liuzhen","machao",["zhoubin","wangcc"])
names[0] = "SUYP"
#>>>执行结果:
>>>TypeError: 'tuple' object does not support item assignment 
#元组类型不支持项赋值
names = ("suyp","lirs","liuzhen","machao",["zhoubin","wangcc"])
names[4][0] = "ZHOUBIN"
print(names[4][0])
# >>>执行结果:
>>>ZHOUBIN
#如果元组内有可元素,这些可变元素的值是可以修改的

 

功能:

index

names = ("suyp","lirs","liuzhen","machao",["zhoubin","wangcc"])
print(names.index("suyp"))
# >>>执行结果:
>>>0
#元组支持index方法,可以快速输出对应索引

count

names = ("suyp","lirs","liuzhen","machao",["zhoubin","wangcc"])
print(names.count("suyp"))
# >>>执行结果:
>>>1
#元组支持.count方法,支持元素计数

切片

names = ("suyp","lirs","liuzhen","machao",["zhoubin","wangcc"])
print(names[0:4])
# >>>执行结果:
>>>('suyp', 'lirs', 'liuzhen', 'machao')
#元组支持切片输出,同列表,顾头不顾尾

使用场景:

显示的告知别人或自己,此处数据定义为不可修改

数据库连接配置信息等

posted @ 2018-03-26 20:37  WudTime  阅读(123)  评论(0编辑  收藏  举报