一.Tuple
1.什么是元祖(tuple)
python提供的容器型數(shù)據(jù)類型,不可變并且有序勤婚。(元祖就是不可變的列表)
- 不可變 - 不支持增刪改,只支持查
- 有序 - 每個(gè)元素對(duì)應(yīng)一個(gè)確定的下標(biāo)
2.字面量和元素
(元素1, 元素2, 元素3...)
其中的元素可以是任何類型的數(shù)據(jù)力崇,并且類型可以不一樣猎拨,同樣的元素可以有多個(gè)
point = (100, 30)
print(point, type(point))
- 注意:
1.空的元祖: ()
tuple1 = ()
print(type(tuple1))
2.只有一個(gè)元素的元祖
tuple2 = (100,)
print(tuple2, type(tuple2))
3.直接將多個(gè)元素用逗號(hào)隔開搁凸,不加小括號(hào)表示也是一個(gè)元祖
tuple3 = 1, 2, 3
print(tuple3, type(tuple3))
3.元祖獲取元素和列表一樣
tuple4 = ('成都', '達(dá)州', '綿陽', '南充', '廣元')
# 獲取單個(gè)元素
print(tuple4[1], tuple4[-1])
# 獲取部分
print(tuple4[0:3])
print(tuple4[::-1])
# 遍歷
for city in tuple4:
print(city)
for index in range(len(tuple4)):
print(tuple4[index])
補(bǔ)充:特殊的獲取方式
- 變量1,變量2... = 元祖 -- 用前面的變量依次獲取元祖元素的值。(要求前面變量的個(gè)數(shù)和元祖元素的個(gè)數(shù)一致)
point = (100, 200, 10)
x, y, z = point # x,y = (100, 200) <==> x, y = 100, 200
print(x, y, z)
- 變量1, 變量2 = 元祖 -- 通過帶的變量獲取元祖中剩余的部分;
注意:這個(gè)結(jié)構(gòu)中帶的變量只能有一個(gè)睦焕,不帶的變量可以有多個(gè)
- 變量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)
補(bǔ)充:*的用法
1.取元祖和列表中的數(shù)據(jù)
nums = (1, 2, 3)
nums2 = [11, 22, 33]
print(*nums, *nums2)
4.相關(guān)運(yùn)算(和列表一樣)
+,*
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.排序
sorted(序列) - 對(duì)序列中的元素排序藐握,產(chǎn)生一個(gè)新的列表(不管是什么序列,排完后最后都是列表)
注意:列表.sort() -- 修改原列表中元素的順序; sorted(列表) -- 產(chǎn)生一個(gè)新的列表
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))
new_str = ''.join(['aks', 'bos', 'cous'])
print(new_str, type(new_str))
list1 = [1, 345, 90, 9]
new_list = list1.sort() # None; sort不會(huì)產(chǎn)生新的列表
print(list1, new_list)
join的使用
- 字符串.join(序列) - 將序列中的元素取出垃喊,用指定的字符串連接在一起猾普。要求序列中的元素必須是字符串
二.dict
1.什么是字典(dict)
python提供的容器型數(shù)據(jù)類型,可變并且無序
- 可變 - 支持元素的增刪改
- 無序 - 不支持下標(biāo)操作
2.字面量和元素
用大括號(hào)括起來本谜,里面多個(gè)鍵值對(duì)初家,每個(gè)鍵值對(duì)用逗號(hào)隔開。鍵值對(duì)就是字典的元素乌助。
{key1:value1, key2:value2, key3:value3...}
鍵值對(duì)- 鍵/key:值/value(鍵值對(duì)); 鍵值對(duì)必須成對(duì)出現(xiàn)溜在,而且脫離字典單獨(dú)出現(xiàn)沒有意義
鍵/key - 必須是不可變的, 而且是唯一的。實(shí)際一般將字符串作為鍵
值/value - 可以是任意類型的數(shù)據(jù)
注意眷茁,字典存儲(chǔ)數(shù)據(jù)炕泳,實(shí)質(zhì)是通過值來存儲(chǔ)的。key是值對(duì)應(yīng)的標(biāo)簽和獲取值的方式
dict1 = {} # 空字典
print(type(dict1))
dict1 = {'a': 100, 10: 200, (1, 2): 'abc', 'a': 111, 'a': [1, 11, 111]}
print(dict1) # {'a': [1, 11, 111], 10: 200, (1, 2): 'abc'}, key唯一
# dict2 = {[1, 2]: 120} # TypeError: unhashable type: 'list'
3.字典額上祈、和列表的選擇
- 什么時(shí)候使用字典:
多個(gè)沒有相同意義的數(shù)據(jù)(需要區(qū)分),就使用字典培遵。例如:保存一個(gè)人的不同信息,一輛車的不同信心 - 什么時(shí)候使用列表:
存儲(chǔ)的多個(gè)數(shù)據(jù)是有相同意義的數(shù)據(jù)(不需要區(qū)分),就使用列表.例如:保存一個(gè)班的學(xué)生信息登刺,保存所有的價(jià)格
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'])
練習(xí): 聲明一個(gè)變量保存一個(gè)班的學(xué)生信息(4個(gè)學(xué)生)籽腕,每個(gè)學(xué)生需要保存姓名,電話和年齡
all_students = [
{'name': '小明', 'tel': '23897823', 'age': 20},
{'name': '張三', 'tel': '238722111', 'age': 28},
{'name': '李四', 'tel': '2111111222', 'age': 18},
{'name': 'xiaohua', 'tel': '111228233', 'age': 30}
]
print(all_students[0])
三.dictItem
字典元素的增刪改查
1.查(獲取值)
注意:字典中的鍵值對(duì)單獨(dú)拎出來沒有任何意義
a.字典[key] - 獲取字典中key對(duì)應(yīng)值
注意: 當(dāng)key不存在的時(shí)候,會(huì)報(bào)KeyError
car = {'color': '黃色', 'type': '跑車', 'price': 500000}
print(car['color'])
print(car['price'])
# print(car['speed']) # KeyError: 'speed'
- b.
- 字典.get(key) - 獲取字典中key對(duì)應(yīng)值; 當(dāng)key不存在的時(shí)候不會(huì)報(bào)錯(cuò)纸俭,并且取到一個(gè)默認(rèn)值None
- 字典.get(key,值1) - 獲取字典中key對(duì)應(yīng)值;當(dāng)key不存在的時(shí)候不會(huì)報(bào)錯(cuò),并且取到指定的值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:
# key
print(key, end=' ')
# value
print(dict1[key])
print(dict1.values(), dict1.items())
# 遍歷字典的values(),獲取所有的值
for value in dict1.values():
print(value)
# values = []
# for key in dict1:
# values.append(dict1[key])
# for value in values:
# print(value)
# 遍歷字典的items(),直接獲取key和value(不建議使用)
for key, value in dict1.items():
print(key, value)
items = []
for key in dict1:
items.append((key, dict1[key]))
for key,value in items:
print(key, value)
2.增皇耗、改
字典[key] = 值 - 當(dāng)key不存在就是添加鍵值對(duì); 當(dāng)key存在的時(shí)候就是修改key對(duì)應(yīng)的值
movie = {'name': '喜羊羊與灰太狼', 'type': '卡通', 'time': 120}
# 添加
movie['score'] = 7.9
print(movie) #{'{'name': '喜羊羊與灰太狼', 'type': '卡通', 'time': 120, 'score': 7.9}
# 修改
movie['type'] = '搞笑'
print(movie)#{'name': '喜羊羊與灰太狼', 'type': '搞笑', 'time': 120, 'score': 7.9}
3.刪(刪除鍵值對(duì))
a.
del 字典[key] - 刪除字典中指定的key對(duì)應(yīng)的鍵值對(duì)
b.
字典.pop(key) - 取出字典中key對(duì)應(yīng)的值
del movie['time']
print(movie)
name = movie.pop('name')
print(movie, name)
練習(xí): 用一個(gè)字典保存一個(gè)學(xué)生的信息: {'name': '張三', 'age': 30, 'score': 80}
輸入需要修改的信息,
例如輸入:name ->修改名字, age -> 修改年齡... abc -> 提示'沒有該信息'
請(qǐng)輸入要修改的信息: name
請(qǐng)輸入新的名字: 李四
{'name': '李四', 'age': 30, 'score': 80}
請(qǐng)輸入要修改的信息: age
請(qǐng)輸入新的年齡: 18
{'name': '張三', 'age': 18, 'score': 80}
請(qǐng)輸入要修改的信息: abc
沒有該信息!
student = {'name': '張三', 'age': 30, 'score': 80}
message = input('請(qǐng)輸入要修改的信息:')
if student.get(message):
if message == 'name':
new_name= input('請(qǐng)輸入新的名字:')
student['name'] = new_name
elif message == 'age':
new_age = int(input('請(qǐng)輸入新的年齡:'))
student['age'] = new_age
else:
new_score = input('請(qǐng)輸入新的分?jǐn)?shù):')
student['score'] = new_score
print(student)
else:
print('沒有該信息!')
四:dictMethod
1.比較運(yùn)算
==, !=
- 注意:判斷兩個(gè)字典是否相等揍很,只看鍵值對(duì)是否一樣郎楼,不管鍵值對(duì)的順序;
字典不支持>和<符號(hào)
print({'a': 11, 'b': 22} == {'b': 22, 'a': 11}) # True
2. 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
3. len(), max(), min()
dict(數(shù)據(jù)) - 數(shù)據(jù)要求是序列万伤,并且序列中的元素都是有兩個(gè)元素的子序列
獲取字典中鍵值對(duì)的個(gè)數(shù)
print(len(dict1))
獲取字典中key的最大值/最小值
print(max(dict1), min(dict1))
將列表轉(zhuǎn)換成字典
print(dict([(1, 2), ('a', 'b'), [10, 'abc']]))
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
- 字典轉(zhuǎn)列表/元祖/集合都是將字典中的key取出來作為列表/元祖/集合的元素
print(list(dict2)) # ['name', 'color', 'height']
4.相關(guān)方法
- 1.字典.clear() - 清空字典
注意:清空容器推薦使用clear操作,而不是重新賦一個(gè)空的容器
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
print(id(dict2))
dict2.clear()
print(dict2, id(dict2))
# 只有容器本身不存在的時(shí)候呜袁,可以使用
dict2 = {}
print(id(dict2))
- 2.字典.copy() - 復(fù)制字典的中的元素敌买,產(chǎn)生一個(gè)新的字典
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
# 直接賦值,修改其中一個(gè)的元素阶界,會(huì)影響另外一個(gè)
dict3 = dict2
print(dict3)
dict3['name'] = '小明'
print(dict3)
print(dict2)
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
# 拷貝賦值虹钮,會(huì)產(chǎn)生新的地址,賦值后相互不影響
dict4 = dict2.copy()
print(dict4)
del dict4['color']
print(dict4)
print(dict2)
- dict.fromkeys(序列, 值) -- 以序列中所有的元素作為key膘融,指定的值作為value創(chuàng)建一個(gè)新的字典
new_dict = dict.fromkeys('abc', (10, 20, 30))
print(new_dict)
new_dict = dict.fromkeys(['name', 'age', 'tel'], 0)
print(new_dict)
字典.keys() - 將字典所有的key取出產(chǎn)生一個(gè)新的序列
字典.values() - 將字典所有的value取出產(chǎn)生一個(gè)新的序列
字典.items() - 將字典所有的key和value做為一個(gè)元祖取出產(chǎn)生一個(gè)新的序列
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
print(dict2.keys(), dict2.values(), dict2.items())
- 5.字典.setdefault(key, value=None)
字典.setdefault(key) - 當(dāng)key不存在的時(shí)候芙粱,添加鍵值對(duì)key:None
字典.setdefault(key, value) - 當(dāng)key不存在的時(shí)候,添加鍵值對(duì)key:value
注意:這個(gè)操作當(dāng)key存在的時(shí)候氧映,不會(huì)修改
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
dict2.setdefault('name2', '小胡')
dict2.setdefault('sex')
print(dict2)
- 字典1.update(字典2) - 使用字典2中的鍵值對(duì)去更新字典1;
如果字典2中的key春畔,字典1中本身存在就是修改,不存在就添加
- 字典1.update(字典2) - 使用字典2中的鍵值對(duì)去更新字典1;
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
dict2.update({'height': 180, 'age': 18})
print(dict2)
dict2.update([('a', 100), ('age', 30)])
print(dict2)
5.Set
1.什么是集合(set)
可變的,無序的; 元素是唯一并且不可變
2.字面量
{元素1, 元素2, 元素3...}
set1 = {1, 23, 'abc'}
print(set1)
# set1 = {1, 23, 'abc', [1, 2]} # TypeError: unhashable type: 'list'
# 表示空集合
set2 = set()
print(type(set2))
set3 = {1, 2, 1, 2, 2}
print(set3)
- 集合自帶去重功能
list1 = [1, 2, 1, 2, 2]
list1 = list(set(list1))
print(list1)
3.增刪改查
set1 = {1, 38, 90, 8}
- 1.查
集合不能單獨(dú)的獲取單個(gè)元素岛都,只能一個(gè)一個(gè)的遍歷
for item in set1:
print(item)
- 2.增
a.集合.add(元素) - 在集合中添加指定的元素
b.集合.update(序列) - 將序列中的元素添加到集合中
set1 = {1, 38, 90, 8}
set1.add('abc')
print(set1)
set1.update('abc')
print(set1)
set1.update({'aa': 10, 'bb': 20})
print(set1)
- 3.刪
集合.remove(元素) --- 刪除集合中指定的元素
set1 = {1, 38, 90, 8}
set1.remove(90)
print(set1)
- 4.數(shù)學(xué)集合運(yùn)算
- 交集(&): 獲取兩個(gè)集合公共的元素產(chǎn)生一個(gè)新的集合
- 并集(|): 將兩個(gè)集合中的元素合并在一起產(chǎn)生一個(gè)新的集合
- 差集(-): 集合1 - 集合2:去掉集合1中包含集合2的部分,剩下的產(chǎn)生一個(gè)新的集合
- 補(bǔ)集(^): 將兩個(gè)集合合并在一起拐迁,去掉公共部分,剩下的部分產(chǎn)生一個(gè)新的集合
- 子集的判斷: 集合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}
補(bǔ)集
print(set1 ^ set2) # {1, 2, 3, 7, 8}
print({1, 2, 3, 9, 18} > {1, 2, 3, 0}) # False
print({1, 2, 3, 9, 18} > {1, 2, 3}) # True疗绣、
print({1, 2, 3} > {1, 2, 3}) # False
print({1, 2, 3} >= {1, 2, 3}) # True