1.什么是元組(tuple)
python提供的容器型數(shù)據(jù)類(lèi)型,不可變并且有序(元組就是不可變的列表)
不可變 - 不支持增刪改俭嘁,只支持查
有序 - 每個(gè)元素都對(duì)應(yīng)一個(gè)確定的下標(biāo)
2.字面量和元素
(元素1, 元素2, 元素3...)
其中的元素可以是任何類(lèi)型的數(shù)據(jù)服猪,并且類(lèi)型可以不一樣罢猪,同樣的元素可以有多個(gè)
point = (100, 30)
print(point, type(point))
注意:
1.空的元組:()
tuple1 = ()
print(type(tuple1))
2.只有一個(gè)元素的元組,元素后要加一個(gè)逗號(hào)才是元組
tuple2 = (100,)
print(tuple2, type(tuple2))
3.直接將多個(gè)元素用逗號(hào)隔開(kāi),不加小括號(hào)表示也是一個(gè)元組
tuple3 = 1, 2, 3
print(tuple3, type(tuple3))
3.元組獲取元素和列表是一樣的
tuple4 = ('成都', '達(dá)州', '綿陽(yáng)', '南充', '廣元')
# 獲取單個(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.變量1, 變量2... = 元組 --> 用前面的變量依次獲取元組中元素的值(要求前面變量的個(gè)數(shù)和元組元素的個(gè)數(shù)一致)
point = (100, 200)
x, y = point # x, y = (100, 200) <==> x, y = 100, 200
print(x, y)
2.變量1, 變量2 = 元組 --> 通過(guò)帶的變量獲取元組中剩余的部分
注意:這個(gè)結(jié)構(gòu)中帶*的變量只能有一個(gè),不帶*的變量可以有多個(gè)
name, *scores = ('小明', 100, 89, 67, 99)
print(name, scores)
*info, num = ('小明', 100, 89, 67, 99)
print(info, num)
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('aa' 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, nums)
new_strs = sorted('ffegwifigeigiegi')
print(str(new_strs), ''.join(new_strs))
join的使用
字符串.join(序列) - 將序列中的元素取出拼坎,用指定的字符串連接在一起泰鸡。要求序列中的元素必須是字符串
new_str = ''.join(['a', 'b', 'c'])
print(new_str, type(new_str))
list1 = [1, 345, 90, 9]
new_list = list1.sort() # None; sort()不會(huì)產(chǎn)生新的列表
print(list1, new_list)
1.什么是字典(dict)
python提供的容器型數(shù)據(jù)類(lèi)型趋惨,可變并且無(wú)序
可變 - 支持元素的增刪改
無(wú)序 - 不支持下標(biāo)操作
2.字面量和元素
用大括號(hào)括起來(lái),里面有多個(gè)鍵值對(duì)讯嫂,每個(gè)鍵值對(duì)用逗號(hào)隔開(kāi)欧芽。鍵值對(duì)就是字典的元素。
{key1:value1, key2:value2, key3:value3...}
鍵值對(duì) - 鍵/key:值/value(鍵值對(duì))憎妙; 鍵值對(duì)必須成對(duì)出現(xiàn)曲楚,而且脫離字典單獨(dú)出現(xiàn)沒(méi)有任何意義
鍵/key - 必須是不可變的龙誊,而且是唯一的。實(shí)際一般將字符串作為鍵
值/value - 可以是任意類(lèi)型的數(shù)據(jù)
注意:字典存儲(chǔ)數(shù)據(jù)鹤树,實(shí)質(zhì)是通過(guò)值來(lái)存儲(chǔ)的逊朽。key是值對(duì)應(yīng)的標(biāo)簽和獲取值的方式
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è)沒(méi)有相同意義的數(shù)據(jù)(需要區(qū)分),就是用字典叽讳。例如:保存一個(gè)人的不同信息,一輛車(chē)的不同信息
什么時(shí)候使用列表:存儲(chǔ)的多個(gè)數(shù)據(jù)是有相同意義的數(shù)據(jù)(不需要區(qū)分)湿酸,就是用列表灭美。例如:保存一個(gè)班的學(xué)生信息届腐,保存所有的價(jià)格
person = {'name': 'xiaohua', 'age': 18, 'sex': 'girl', 'height': 160, 'weight': 90, 'score': 89}
print(person['name'])
練習(xí):聲明一個(gè)變量蜂奸,保存一個(gè)班的學(xué)生信息(4個(gè)學(xué)生),每個(gè)學(xué)生需要保存姓名围详,電話和年齡
all_students = [
{'name': 'xiaoming', 'tel': 1352654215, 'age': 18},
{'name': 'xiaohua', 'tel': 1538337373, 'age': 17},
{'name': 'xiaogou', 'tel': 137777215, 'age': 20},
{'name': 'xiaoguang', 'tel': 1375755, 'age': 17}
]
print(all_students[0])
字典元素的增刪改查
1.查(獲取值)
注意:字典中的鍵值對(duì)單獨(dú)拿出來(lái)沒(méi)有任何意義
a.字典[key] - 獲取字典中key對(duì)應(yīng)的值
注意:當(dāng)key不存在的時(shí)候助赞,會(huì)報(bào)KeyError
car = {'color': '黃色', 'type': '跑車(chē)', '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', 100)) # 100
c.遍歷字典
注意:直接通過(guò)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)
# 相當(dāng)于
# 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)
# 相當(dāng)于
# items = []
# for key in dict1:
# items.append((key, dict1[key]))
# for key, value in items:
# print(key, value)
2.增赎离、改
字典[key] = 值 - 當(dāng)key不存在時(shí)就是添加鍵值對(duì);當(dāng)key存在時(shí)就修改key對(duì)應(yīng)的值
movie = {'name': '喜羊羊與灰太狼', 'type': '卡通', 'time': 120}
# 添加
movie['score'] = 7.9
print(movie)
# 修改
movie['type'] = '搞笑'
print(movie)
3.刪(刪除鍵值對(duì))
a. del 字典[key] - 刪除字典中指定的key對(duì)應(yīng)的鍵值對(duì)
del movie['time']
print(movie)
b. 字典.pop(key) - 取出字典中key對(duì)應(yīng)的值
name = movie.pop('name')
print(movie, name)
練習(xí):用一個(gè)字典保存一個(gè)學(xué)生的信息:{'name': '張三', 'age': 30, 'score': 80}
輸入需要修改的信息圾浅,例如輸入:name -> 修改名字狸捕, age -> 修改年齡...abc -> 提示'沒(méi)有該信息'
stu = {'name': '張三', 'age': 30, 'score': 80}
while True:
change_message = input('請(qǐng)輸入需要修改的信息(輸入\'end\'來(lái)結(jié)束輸入):')
if change_message == 'end':
break
if stu.get(change_message):
if change_message == 'name':
new_name = input('請(qǐng)輸入新的名字:')
stu['name'] = new_name
elif change_message == 'age':
new_age = int(input('請(qǐng)輸入新的年齡:'))
stu['age'] = new_age
else:
new_score = float(input('請(qǐng)輸入新的成績(jī):'))
stu['score'] = new_score
print(stu)
else:
print('沒(méi)有該信息')
# student = {'name': '張三', 'age': 30, 'score': 80}
# message = input('請(qǐng)輸入要修改的信息:')
# if student.get(message):
# if message == 'name':
# new_name = input('請(qǐng)輸入新的名字:')
# student[message] = new_name
# elif message == 'age':
# new_age = int(input('請(qǐng)輸入新的年齡:'))
# student['age'] = new_age
# else:
# new_score = float(input('請(qǐng)輸入新的成績(jī):'))
# student['score'] = new_score
# print(student)
# else:
# print('沒(méi)有該信息')
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, 'b': 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))
# 獲取字典中key的最小值
print(min(dict1))
# 將列表轉(zhuǎn)換成字典
print(dict([(1, 2), ('a', 'b'), [10, 'abc']]))
# 字典轉(zhuǎn)列表/元組/集合都是將字典中的key取出來(lái)作為列表/元組/集合的元素
dict2 = {'name': 'xiaohua', 'color': 'black', 'height': 170}
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() - 賦值字典中的元素铅祸,產(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)生新的地址,復(fù)制后相互不影響
dict4 = dict2.copy()
print(dict4)
del dict4['color']
print(dict4)
print(dict2)
3. dict.fromkeys(seq, val) -- 以序列中所有的元素作為key萎津,指定的值作為value創(chuàng)建一個(gè)新的字典
new_dict = dict.fromkeys('abc', 100)
print(new_dict)
new_dict = dict.fromkeys(['name', 'age', 'tel'], 0)
print(new_dict)
4.
字典.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)
6.字典1.update(字典2) - 使用字典2中的鍵值對(duì)去更新字典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)
可變的牙捉,無(wú)序的;元素是唯一并且不可變
2.字面量
{元素1, 元素2芬位, 元素3...}
set1 = {1, 23, 5, 'abc'}
print(set1)
# set1 = {1, 23, 5, 'abc', [1, 2]} # TypeError: unhashable type: 'list'
# print(set1)
# 表示空集合
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.增刪查
1.查
集合不能單獨(dú)的獲取單個(gè)元素昧碉,只能一個(gè)一個(gè)的遍歷
set1 = {1, 28, 90, 8}
for item in set1:
print(item)
2.增
a. 集合.add(元素) - 在集合當(dāng)中添加指定的元素
b. 集合.update(序列) - 將序列中的元素添加到集合中
set1 = {1, 28, 90, 8}
set1.add('abc')
print(set1)
set1.update('abc')
print(set1)
set1.update({'name': '張三', 'age': 18})
print(set1)
3.刪
集合.remove(元素) - 刪除集合中指定的元素
set1 = {1, 28, 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 -> 判斷集合2中是否包含集合1
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
# 交集
print(set1 & set2) # {4, 5, 6}
# 并集
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9}
# 差集
print(set2 - set1) # {8, 9, 7}
print(set1 - set2) # {1, 2, 3}
# 補(bǔ)集
print(set1 ^ set2) # {1, 2, 3, 7, 8, 9}
# 子集的判斷
print({1, 2, 3, 9, 18} > {1, 2, 3}) # True
print({1, 2, 3, 9, 18} > {1, 2, 3, 0}) # False
print({1, 2, 3} >= {1, 2, 3}) # True
print({1, 2, 3} > {1, 2, 3}) # False