一.元祖
1.什么是元祖(tuple)
python提供的容器型數(shù)據(jù)類型,不可變并且有序。(元祖就是不可變的列表)
不可變 - 不支持增刪改,只支持查。
例如:
point = (100, 30)
a.空的元祖: ()
tuple1 = ()
b.只有一個元素的元祖
print(tuple2, type(tuple2))
有序 - 每個元素對應一個確定的下標
2.字面量和元素
(元素1, 元素2, 元素3...)
其中的元素可以是任何類型的數(shù)據(jù)沼头,并且類型可以不一樣,同樣的元素可以有多個歹篓。
例如:
tuple3 = 1, 2, 3
3.元祖獲取元素和列表一樣
tuple4 = ('成都', '達州', '綿陽', '南充', '廣元')
a.獲取單個元素
print(tuple4[1], tuple4[-1])
b.獲取部分
print(tuple4[0:3])
print(tuple4[::-1])
4.補充:特殊的獲取方式
a. 變量1,變量2... = 元祖 -- 用前面的變量依次獲取元祖元素的值瘫证。(要求前###面變量的個數(shù)和元祖元素的個數(shù)一致)
point = (100, 200, 10)
x, y, z = point # x,y = (100, 200) <==> x, y = 100, 200
print(x, y, z)
b. 變量1, 變量2 = 元祖 -- 通過帶的變量獲取元祖中剩余的部分;
注意:這個結構中帶的變量只能有一個,不帶的變量可以有多個庄撮。
name, *scores = ('小明', 100, 89, 67, 99)
print(name, scores)
name, num, *scores = ('小明', 100, 89, 67, 99)
print(name, num, scores)
*info, num1, num2 = ('小明', 100, 89, 67, 99)
print(info, num1, num2)
info1, *nums, num1 = ('小明', 100, 89, 67, 99)
print(nums)
c. 補充:*的用法
取元祖和列表中的數(shù)據(jù)
nums = (1, 2, 3)
nums2 = [11, 22, 33]
print(*nums, *nums2)
4.相關運算(和列表一樣)
+,*
in / not in
len(), max(), min(), sum(), tuple()
tuple1 = (1, 2, 3)
tuple2 = ('aa', 'bb')
print(tuple1 + tuple2)
print(tuple1*3)
print('aaa' in tuple2)
5.排序
a. sorted(序列) - 對序列中的元素排序背捌,產生一個新的列表(不管是什么序列,排完后最后都是列表)
注意:列表.sort() -- 修改原列表中元素的順序; sorted(列表) -- 產生一個新的列表
nums = (1, 34, 89, 9)
new_nums = sorted(nums, reverse=True)
print(new_nums, tuple(new_nums),nums)
new_strs = sorted('skjhabssnssalewz')
print(str(new_strs), ''.join(new_strs))
b. join的使用
字符串.join(序列) - 將序列中的元素取出洞斯,用指定的字符串連接在一起毡庆。要求序列中的元素必須是字符串
new_str = ''.join(['aks', 'bos', 'cous'])
print(new_str, type(new_str))
list1 = [1, 345, 90, 9]
new_list = list1.sort() # None; sort不會產生新的列表
print(list1, new_list)
二.字典
1.什么是字典(dict)
python提供的容器型數(shù)據(jù)類型,可變并且無序
可變 - 支持元素的增刪改
無序 - 不支持下標操作
2.字面量和元素
用大括號括起來烙如,里面多個鍵值對么抗,每個鍵值對用逗號隔開。鍵值對就是字典的元素亚铁。
{key1:value1, key2:value2, key3:value3...}
鍵值對- 鍵/key:值/value(鍵值對); 鍵值對必須成對出現(xiàn)蝇刀,而且脫離字典單獨出現(xiàn)沒有意義。
鍵/key - 必須是不可變的, 而且是唯一的徘溢。實際一般將字符串作為鍵
值/value - 可以是任意類型的數(shù)據(jù)
注意:字典存儲數(shù)據(jù)吞琐,實質是通過值來存儲的。key是值對應的標簽和獲取值的方式然爆。
3.什么時候使用字典:多個沒有相同意義的數(shù)據(jù)(需要區(qū)分),就使用字典站粟。
例如:保存一個人的不同信息,一輛車的不同信息曾雕。
什么時候使用列表: 存儲的多個數(shù)據(jù)是有相同意義的數(shù)據(jù)(不需要區(qū)分),就使用列表.例如:保存一個班的學生信息奴烙,保存所有的價格。
person = ['xiaohua', 18, 'girl', 160, 90, 89]
print(person[1])
person[-2]
person = {'name': 'xiaohua', 'age': 18, 'sex': 'girl', 'height': 160, 'weight': 90, 'score': 89}
print(person['age'])
4.字典元素的增刪改查
a.查(獲取值)
注意:字典中的鍵值對單獨拎出來沒有任何意義
1.字典[key] - 獲取字典中key對應值
注意: 當key不存在的時候剖张,會報KeyError
b.
字典.get(key) - 獲取字典中key對應值; 當key不存在的時候不會報錯切诀,并且取到一個默認值None
字典.get(key,值1) - 獲取字典中key對應值;當key不存在的時候不會報錯,并且取到指定的值1
print(car.get('type'))
print(car.get('speed'))
print(car.get('color', '紅色')) # 黃色
print(car.get('speed', 0)) # 0
c.遍歷字典
注意: 直接通過for-in遍歷字典取到的是key
dict1 = {'a': 100, 'b': 200, 'c': 300}
- 遍歷字典取到的是key(推薦使用)
for key in dict1:
print(key, end=' ')
print(dict1[key])
print(dict1.values(), dict1.items())
- 遍歷字典的values(),獲取所有的值
for value in dict1.values():
print(value)
3.遍歷字典的items(),直接獲取key和value(不建議使用)
for key, value in dict1.items():
print(key, value)
2.增、改
字典[key] = 值 - 當key不存在就是添加鍵值對; 當key存在的時候就是修改key對應的值
movie = {'name': '喜羊羊與灰太狼', 'type': '卡通', 'time': 120}
a. 添加
movie['score'] = 7.9
print(movie)
b. 修改
movie['type'] = '搞笑'
print(movie)
3.刪(刪除鍵值對)
a.
del 字典[key] - 刪除字典中指定的key對應的鍵值對
b.
字典.pop(key) - 取出字典中key對應的值
del movie['time']
print(movie)
name = movie.pop('name')
print(movie, name)
4.比較運算
==, !=
注意:判斷兩個字典是否相等搔弄,只看鍵值對是否一樣趾牧,不管鍵值對的順序;
字典不支持>和<符號
print({'a': 11, 'b': 22} == {'b': 22, 'a': 11})
# True
a. in / not in
key in 字典 --- 判斷字典中指定的key是否存在
key not in 字典 --- 判斷字典中指定的key是否不存在
dict1 = {'a': 1, 'z': 2, 'c': 3}
print('a' in dict1) # True
print(1 in dict1) # False
5. len(), max(), min()
a.dict(數(shù)據(jù)) - 數(shù)據(jù)要求是序列,并且序列中的元素都是有兩個元素的子序列
1.獲取字典中鍵值對的個數(shù)
print(len(dict1))
2. 獲取字典中key的最大值/最小值
print(max(dict1), min(dict1))
3. 將列表轉換成字典
print(dict([(1, 2), ('a', 'b'), [10, 'abc']]))
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
4. 字典轉列表/元祖/集合都是將字典中的key取出來作為列表/元祖/集合的元素
print(list(dict2)) # ['name', 'color', 'height']
6.相關方法
a.字典.clear() - 清空字典
注意:清空容器推薦使用clear操作肯污,而不是重新賦一個空的容器
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
print(id(dict2))
dict2.clear()
print(dict2, id(dict2))
b.只有容器本身不存在的時候,可以使用
dict2 = {}
print(id(dict2))
c.字典.copy() - 復制字典的中的元素,產生一個新的字典
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
d. 直接賦值蹦渣,修改其中一個的元素哄芜,會影響另外一個
dict3 = dict2
print(dict3)
dict3['name'] = '小明'
print(dict3)
print(dict2)
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
e. 拷貝賦值,會產生新的地址柬唯,賦值后相互不影響
dict4 = dict2.copy()
print(dict4)
del dict4['color']
print(dict4)
print(dict2)
f. dict.fromkeys(序列, 值) -- 以序列中所有的元素作為key认臊,指定的值作為value創(chuàng)建一個新的字典
new_dict = dict.fromkeys('abc', (10, 20, 30))
print(new_dict)
new_dict = dict.fromkeys(['name', 'age', 'tel'], 0)
print(new_dict)
g.
字典.keys() - 將字典所有的key取出產生一個新的序列
字典.values() - 將字典所有的value取出產生一個新的序列
字典.items() - 將字典所有的key和value做為一個元祖取出產生一個新的序列
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
print(dict2.keys(), dict2.values(), dict2.items())
h.字典.setdefault(key, value=None)
字典.setdefault(key) - 當key不存在的時候,添加鍵值對key:None
字典.setdefault(key, value) - 當key不存在的時候锄奢,添加鍵值對key:value
注意:這個操作當key存在的時候失晴,不會修改
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
dict2.setdefault('name2', '小胡')
dict2.setdefault('sex')
print(dict2)
i. 字典1.update(字典2) - 使用字典2中的鍵值對去更新字典1;
如果字典2中的key,字典1中本身存在就是修改,不存在就添加
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
dict2.update({'height': 180, 'age': 18})
print(dict2)
dict2.update([('a', 100), ('age', 30)])
print(dict2)
三.集合
1.什么是集合(set)
可變的拘央,無序的; 元素是唯一并且不可變
2.字面量
{元素1, 元素2, 元素3...}
3.增刪改查
set1 = {1, 38, 90, 8}
a.查
集合不能單獨的獲取單個元素涂屁,只能一個一個的遍歷
for item in set1:
print(item)
b.增
1.集合.add(元素) - 在集合中添加指定的元素
2.集合.update(序列) - 將序列中的元素添加到集合中
set1 = {1, 38, 90, 8}
set1.add('abc')
print(set1)
set1.update('abc')
print(set1)
set1.update({'aa': 10, 'bb': 20})
print(set1)
c.刪
集合.remove(元素) --- 刪除集合中指定的元素
set1 = {1, 38, 90, 8}
set1.remove(90)
print(set1)
d.數(shù)學集合運算
交集(&): 獲取兩個集合公共的元素產生一個新的集合
并集(|): 將兩個集合中的元素合并在一起產生一個新的集合
差集(-): 集合1 - 集合2:去掉集合1中包含集合2的部分,剩下的產生一個新的集合
補集(^): 將兩個集合合并在一起,去掉公共部分灰伟,剩下的部分產生一個新的集合
子集的判斷: 集合1>集合2 -> 判斷集合1中是否包含集合2, 集合1<集合2 - 判斷集合1中是否包含集合2
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8}
# 交集
print(set1 & set2) # {4, 5, 6}
# 并集
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8}
# 差集
print(set1 - set2) # {1, 2, 3}
# 補集
print(set1 ^ set2) # {1, 2, 3, 7, 8}