01tuple
簡單總結:
tuple1 = () # 空元祖
tuple1 = (1, 2, 'ab', 5) # 字面量和元素
x, y, z, a = tuple1 # 獲取元素
x, y = tuple1 # 獲取元素
x, y, z = tuple # 獲取元素
list1 = [1, 2, 3, 'ab', 3]
print(tuple) # 一個一個的取元素
print(list1) # 一個一個的取元素
new_list = sorted(tuple1) # 對原序列進行排序祟偷,返回一個新列表
字符串.join(seq) # 將序列中的元素取出,用指定的字符串連接载庭,序列中的元素必須是字符串
''.join(seq) # 針對sorted(序列)返回列表的用法勾哩,實現(xiàn)最終返回無間隔的字符串
詳細總結:
1. 什么是元組(Tuple)
python提供的容器型數據類型七蜘,不可變并且有序。(元組就是不可變的列表)
不可變 - 不支持增刪改,只支持查
有序 - 每一個元素對應一個確定的下標
2. 字面量和元素
(元素1赊琳,元素2,元素3......)
其中的元素可以是任何類型的數據砰碴,并且類型可以不一樣躏筏,同樣的元素可以有多個
point = (100, 30)
print(point, type(point))
注意:
1. 空的元祖:()
tuple1 = ()
print(type(tuple1))
2. 只有一個元素的元祖
tuple2 = (100,) # 必須加一個逗號,否則不是元祖類型
print(tuple2, type(tuple2))
3. 直接將多個元素用逗號隔開呈枉,不加小括號趁尼,表示也是一個元祖
tuple3 = 1, 2, 3
print(tuple3, type(tuple3))
3. 元祖獲取元素和列表一樣
tuple4 = ('成都', '達州', '綿陽', '南充', '廣元')
# 獲取單個元素
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])
補充:特殊的獲取方式
1. 變量1, 變量2... = 元祖 -- 用前面的變量依次獲取元祖中元素的值猖辫。(要求前面變量的個數和元祖元素的個數一致)
point = (100, 200)
x, y = point # x, y = (100, 200) <==> x, y = 100, 200
print(x, y)
2. 變量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)
info, *nums, num1 = ('小明', 100, 89, 67,99)
print(nums)
補充:*的用法
1. 取元祖和列表中的數據
nums = (1, 'abc', 2, 3)
nums2 = [11, 22, 33]
print(*nums, *nums2)
# 2. 取字典中的元素, 脫離函數無用
# dict1 = {'a':1, 'b':2}
# print(**dict1)
4. 相關運算(和列表一樣)
+啃憎, *
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(序列) - 對序列中的元素排序芝囤,產生一個新的序列(不管是什么序列,排完后最后都是列表)
注意: 列表.sort() -- 修改原列表中元素的順序辛萍; sorted(列表) -- 產生一個新的列表
nums = (1, 34, 554, 34,23)
new_nums = sorted(nums, reverse = True)
print(new_nums, tuple(new_nums), nums)
new_strs = sorted('dsgvcdgavnk')
print(new_strs, ''.join(new_strs))
補充:join的使用
字符串.join(序列) - 將序列中的元素取出悯姊,用指定的字符串連接在一起。要求序列中的元素必須是字符串
new_str = ''.join(('adsf', 'd', 'ggd'))
print(new_str, type(new_str))
02 dict
1. 什么是字典(dict)
python提供的容器型數據類型贩毕,可變并且無序
可變 - 支持元素的增刪改
無序 - 不支持下標操作
2. 字面量和元素
用大括號括起來悯许,里面多個鍵值對,每個鍵值對用逗號隔開辉阶。鍵值對就是字典的元素先壕。
{key1:value1, key2:value2, key3:value3......}
鍵值對 - 鍵/key : 值/value(這就是鍵值對);鍵值對必須成對出現(xiàn),而且脫離字典單獨出現(xiàn)沒有意義
鍵/key - 必須是不可變的谆甜,而且是唯一的垃僚。實際一般將字符串作為鍵
值/value - 可以是任意類型的數據
注意,字典存儲數據规辱,實質是通過值來存儲的谆棺,key是值對應的標簽和獲取值的方式
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. 什么時候使用字典:多個沒有相同意義的數據(需要區(qū)分)按摘,就使用字典包券。
例如:保存一個人的不同信息纫谅,一輛車的不同信息。
什么時候使用列表:存儲的多個數據是有相同意義的數據(不需要區(qū)分)溅固,就使用列表付秕。
例如:保存一個班的學生信息,保存所有的價格
person = ['xiaohua', 18, 'girl', 160, 90]
print(person[0])
person = {'name': 'xiaohua', 'age': 18, 'sex': 'girl', 'height': 160, 'weight': 90, 'scores': 89}
print(person['age'])
練習:聲明一個變量保存一個班的學生信息(4個學生)侍郭,每個學生需要保存询吴,姓名、電話亮元、年齡
all_student = [
{'name': 'xiaoming', 'tel': '3467452', 'age': 21},
{'name': 'xiaohong', 'tel': '84646362', 'age': 23},
{'name': 'xiaoli', 'tel': '676562', 'age': 24},
{'name': 'xiaohua', 'tel': '325654', 'age': 22}
]
print(all_student[0])
03 dict item
字典的增刪改查
1. 查(獲取值)
注意:字典中的鍵值對單獨拎出來沒有任何意義
a. 字典[key] - 獲取字典中key對應的值
注意:當key不存在的時候猛计,會報KeyError
"""
car = {'color': '黃色', 'type': '跑車', 'price': 500000}
print(car['color'])
print(car['price'])
# print(car['speed']) # KeyError: 'speed'
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', 100)) # 100
print(car)
c. 遍歷字典
注意:直接通過for-in遍歷字典取到的是key
dict1 = {'a': 100, 'b': 200, 'c': 300}
# 遍歷字典取到的是key(推薦使用)
for key in dict1:
# key
print(key, end = ' ')
# value
print(dict1[key])
# 遍歷字典的values()煮甥,獲取所有的值
for value in dict1.values():
print(value)
# 遍歷字典的items()盗温,直接獲取key和value (不建議使用)
for key, value in dict1.items():
print(key, value)
2. 增、改
a.
字典[key] = 值 - 當key不存在就是添加鍵值對成肘;當key存在的時候就是修改key對應的值
movie = {'name': '喜洋洋與灰太狼', 'type': '卡通', 'time': 120}
添加
movie['score'] = 7.9
print(movie)
修改
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)
練習:用一個字典保存一個學生的信息:{'name': '張三', 'age': 30, 'score': 80}
輸入需要修改的信息卖局,例如輸入:name -> 修改名字, age -> 修改年齡... abc -> 提示'沒有該信息'
請輸入要修改的信息:name
請輸入新的名字:李四
{'name': '李四', 'age': 30, 'score': 80}
請輸入要修改的信息:abc
沒有該信息双霍!
student = {'name': '張三', 'age': 30, 'score': 80}
message = input('請輸入要修改的信息:')
if message in student:
value = input('請輸入新的值:')
student[message] = value
print(student)
else:
print('沒有該信息砚偶!')
# 老師的解,我的改進:
student = {'name': '張三', 'age': 30, 'score': 80}
message = input('請輸入要修改的信息:')
if student.get(message):
new_value = input('請輸入新的值:')
student[message] = new_value
print(student)
else:
print('沒有該信息洒闸!')
# 老師的解:
student = {'name': '張三', 'age': 30, 'score': 80}
message = input('請輸入要修改的信息:')
if student.get(message):
if message == 'name':
new_name = input('請輸入新的名字:')
student[message] = new_name
elif message == 'age':
new_age = input('請輸入新的年齡')
student[message] = new_age
else:
new_score = input('請輸入新的分數:')
student['score'] = new_score
print(student)
else:
print('沒有該信息染坯!')
04 dict Method
簡單總結:
"""
dict1 = {} # 空字典
dict1 = {key1: value, key2: value ...} # 字典字面量和元素
dict1[key] # 查找字典
dict1.get(key) # 查找字典,如果key不存在不會報錯顷蟀,存在則默認返回None
dict1.get(key, value) # 查找字典酒请,如果key不存在不會報錯骡技,存在則返回value
dict1[key] = value # 如果key存在鸣个,修改key的值,如果key不存在布朦,增加鍵值對key:value
del dict1[key] # 刪除鍵值對
dict1.pop(key) # 取出鍵值對
dict.clear() # 清空字典
dict.copy() # 復制字典
dict.fromkeys(seq, value) # 以序列中的元素作為key囤萤,每個key對應的值都為value,產生一個新的字典
dict.keys() # 獲取字典中所有的key
dict.values() # 獲取字典中所有的value
dict.items() # 獲取字典中所有的key:value
dict.setdefault(key, value) # 只添加不修改是趴。當key不存在涛舍,添加key:value,value默認值是None唆途。當key存在富雅,不做修改
dict1.update(dict2) # 更新字典掸驱。將字典2增加到字典1中。如果字典2中的key在字典1中存在没佑,就修改值毕贼,不存在就添加鍵值對
"""
詳細總結:
1. 比較運算
==, !=
注意:判斷兩個字典是否相等,只看鍵值對是否一樣蛤奢,不管鍵值對的順序鬼癣;
字典不支持 > 和 < 符號
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(), sum(), dict()
字典求和意義不大
dict(數據) - 數據要求是序列,并且序列中的元素都是有兩個元素的子序列
# 獲取字典中鍵值對的個數
print(len(dict1))
# 獲取字典中key的最大值/最小值
print(max(dict1), min(dict1))
# 將列表轉換成字典
print(dict([(1, 2), ('a', 'b'), [10, 'vvv']]))
dict2 = {'name': 'xiaohong', 'color': 'black', 'height': 170}
# 字典轉列表/元祖/集合都是將字典中的key取出來作為列表/元祖/集合的元素
print(list(dict2)) # ['name', 'color', 'height']
4. 相關方法
- 字典.clear() - 清空字典
注意:清空容器推薦使用clear操作啤贩,而不是重新賦一個空的容器
dict2 = {'name': 'xiaohong', 'color': 'black', 'height': 170}
dict2.clear()
print(dict2)
print(id(dict2))
只有容器本身不存在的時候待秃,可以使用
dict2 = {}
print(id(dict2))
- 字典.copy() - 復制字典中的元素,產生一個新的字典
dict2 = {'name': 'xiaohong', 'color': 'black', 'height': 170}
直接賦值痹屹,修改其中一個的元素章郁,會影響另外一個
dict3 = dict2
dict3['name'] = '小明'
print(dict3)
print(dict2)
dict2 = {'name': 'xiaohong', 'color': 'black', 'height': 170}
拷貝賦值,會產生新的地址志衍,賦值后相互不影響
dict4 = dict2.copy()
print(dict4)
del dict4['color']
print(dict4)
print(dict2)
- dict.fromkeys(seq, val) -- 以序列中所有的元素作為key驱犹,指定的值作為value創(chuàng)建一個新的字典
new_dict = dict.fromkeys('abc', 100)
print(new_dict)
new_dict = dict.fromkeys(['name', 'age', 'tel'], 20)
print(new_dict)
字典.keys() - 將字典所有的keys取出產生一個新的序列
字典.values() - 將字典所有的values取出產生一個新的序列
字典.items() - 將字典所有的key和value作為一個元祖取出產生一個新的序列
dict2 = {'name': 'xiaohong', 'color': 'black', 'height': 170}
print(dict2.keys(), dict2.values(), dict2.items())
- 字典.setdefault(key, value=None)
字典.setdefault(key) - 當key不存在的時候,添加鍵值對key:None
字典.setdefault(key,value) - 當key不存在的時候足画,添加鍵值對key:value
注意:這個操作當key存在的時候雄驹,不會修改
dict2 = {'name': 'xiaohong', 'color': 'black', 'height': 170}
dict2.setdefault('name', '小胡')
print(dict2)
dict2.setdefault('sex')
print(dict2)
dict2.setdefault('name2', '小胡')
print(dict2)
- 字典.update(字典2) - 使用字典2中的鍵值對,去更新字典1;
如果字典2中的key淹辞,字典1中本身存在就是修改医舆,不存在就添加
dict2 = {'name': 'xiaohong', 'color': 'black', 'height': 170}
dict2.update({'height': 190, 'age': 18})
print(dict2)
dict2.update([('a', 100), ('age', 30)])
print(dict2)