一廷蓉、元組
Python的元組與列表類似全封,不同之處在于元組的元素不能修改。元組使用小括號桃犬,列表使用方括號刹悴。
1.1 元組的格式
格式
變量名=(,,,,)
案例
aTuple=(23,35,56,34,11,21)
1.2 訪問元組
通過索引取數(shù)據(jù)
案例:索引值存在
aTuple=(23,35,56,34,11,21)
print(aTuple[2])
案例:索引值不存在
aTuple=(23,35,56,34,11,21)
print(aTuple[20])
1.3 查詢個數(shù)
count查詢出現(xiàn)的個數(shù)
案例
aTuple=('b','c','d','e','f','g')
print(aTuple.count('d'))
1.4 查詢索引
index:查詢元素的索引,有對應(yīng)的元素返回對應(yīng)的索引攒暇,否則報錯
案例:有對應(yīng)的元素
aTuple=('b','c','d','e','f','g')
print(aTuple.index('d',0,4))
案例:無對應(yīng)的元素
aTuple=('b','c','d','e','f','g')
print(aTuple.index('d',0,1))
1.5 修改數(shù)據(jù)(不能修改)
案例
aTuple=('b','c','d','e','f','g')
aTuple[1]=23
1.6 類型轉(zhuǎn)換
列表轉(zhuǎn)換元組
案例
aa = [23,34,45,56,67]
tuple(aa)
print(aa)
元組轉(zhuǎn)換列表
案例
aTuple=('b','c','d','e','f','g')
a = list(aTuple)
print(a)
1.7 元組的循環(huán)取值
方式一:for
aTuple=('b','c','d','e','f','g')
for i in aTuple:
print(i)
方式二:while
aTuple=('b','c','d','e','f','g')
i=0
while i < len(aTuple):
print(aTuple[i])
i=i+1
二土匀、字典
2.1 字典的格式
格式
變量名={key1:value,key2:value,,,}
案例
info = {"name":"anfly","age":12,"sex":"男"}
字典的每個元素由2部分組成,鍵(key):值(value)
2.2 根據(jù)鍵訪問值
案例:有對應(yīng)key的
info = {"name":"anfly","age":18,"sex":"男"}
print(info["name"])
案例:無對應(yīng)key的
info = {"name":"anfly","age":12,"sex":"男"}
print(info["name12"])
假如我們不確定字典中是否存在某個鍵而又想獲取其值時,如何操作形用?
案例:有對應(yīng)key的
info = {"name":"anfly","age":12,"sex":"男"}
print(info.get("name"))
案例:無對應(yīng)key的
info = {"name":"anfly","age":12,"sex":"男"}
print(info.get("name"))
案例:無對應(yīng)key的,默認(rèn)返回數(shù)據(jù)
info = {"name":"anfly","age":12,"sex":"男"}
print(info.get("name12","無數(shù)據(jù)"))
2.3 修改元素
字典的每個元素中的數(shù)據(jù)是可以修改的就轧,只要通過key找到,即可修改,否則是新增
案例:對應(yīng)的key
info = {"name":"anfly","age":12,"sex":"男"}
info["age"] =14
print(info)
案例:無對應(yīng)的key
info = {"name":"anfly","age":12,"sex":"男"}
info["gender"] ="屬雞"
print(info)
總結(jié)
有對應(yīng)的key則是修改數(shù)據(jù)田度,沒有對應(yīng)的key是新增數(shù)據(jù)
2.4 添加元素
案例:
info = {"name":"anfly","age":12,"sex":"男"}
info["gender"] ="屬雞"
print(info)
2.5 刪除元素
del,clear() ---- 清空
2.5.1 del (刪除指定的元素)
案例:刪除整個字典
info = {"name":"anfly","age":12,"sex":"男"}
del info
print(info)
案例:刪除某個元素
info = {"name":"anfly","age":12,"sex":"男"}
del info["name"]
print(info)
2.5.2 clear清空
案例:
info = {"name":"anfly","age":12,"sex":"男"}
info.clear()
print(info)
2.6 查詢長度
len():查詢鍵值對的個數(shù)
案例
info = {"name":"anfly","age":12,"sex":"男"}
print(len(info))
2.7 字典中循環(huán)
案例:取出字典中的key
info = {"name":"anfly","age":12,"sex":"男"}
for i in info.keys():
print(i)
結(jié)果:name age sex
案例:取出字典中的value
info = {"name":"anfly","age":12,"sex":"男"}
for i in info.values():
print(i)
結(jié)果:anfly 12 男
取出字典中的key和value
方式一:
info = {"name":"anfly","age":12,"sex":"男"}
for i in info.keys():
print(i,info[i])
方式二:
info = {"name":"anfly","age":12,"sex":"男"}
for k,v in info.items():
print(k,v)