一崎岂、復習(列表)
1.容器捆毫,可以同時存放多個數據〕甯剩可變绩卤,有序
2.元素,可以是任何類型的數據江醇,一個列表可以同時存放不同類型的數據
3.元素的增刪改查
查 --> 列表[下標]濒憋, 列表[:],列表[::]陶夜,遍歷
增 --> append(元素), insert(下標,元素), extend(序列)
刪除 --> del 列表[下標], remove(元素), pop(),pop(下標), clear()
改 --> 列表[下標] = 新值
4.+, *, ==, is, in, not in, len(), max(), min(), list()
二凛驮、元祖
1.什么是元祖
使用()將多個元素括起來,多個元素之間用逗號隔開
a.
容器条辟,可以同時存儲多個數據,不可變的黔夭,有序的
不可變 ---> 不能增刪改
有序 ---> 可以通過下標獲取元素
b.
元素,可以是任何類型的數據
tuple1 = (1, 'yue', True, [1, 2], lambda s:s*2)
print(tuple1)
注意:1.如果元祖的元素只有一個的時候羽嫡,必須在元素的后面加逗號
tuple2 = (100,)
print(type(tuple2))
2.多個數據直接用逗號隔開本姥,表示的也是一個元祖
tuple2 = 10, 20, 'abc'
print(tuple2, type(tuple2))
2.元素的查
元祖的元素不支持增刪改
列表獲取元素的方式,元祖都支持:元祖[下標],
元祖[:], 元祖[::]
遍歷:和列表一樣
tuple2 = ('星期一', '星期二', '星期三', '星期四')
print(tuple2[1]) 星期二
print(tuple2[2:]) ('星期三', '星期四')
print(tuple2[::-1]) ('星期四', '星期三', '星期二', '星期一')
遍歷
for item in tuple2:
print(item)
index = 0
while index < len(tuple2):
print(tuple2[index])
index += 1
補充:獲取部分元素
可以通過相同的變量個數杭棵,來一一獲取元祖中的元素
x, y = (10, 20)
print(x, y) 10 20
x, y, z = (10, 20, 30)
x, y = 10, 20
1.應用:交換兩個數的值
a = 10
b = 20
方法1:
t = a # t = 10
a = b # a = 20
b = t # b = 10
方法2:
a, b = b, a # a,b = (b,a) = (20, 10)
可以通過在變量前加*來獲取部分的元素(適用于列表)
tuple2 = ('小明', 90, 89, 67, 100)
name, *score = tuple2
print(name, score) # 小明 [90, 89, 67, 100]
tuple2 = (90, 89, 67, 100, '小明')
*score, name = tuple2
print(score, name) # [90, 89, 67, 100] 小明
tuple2 = ['boy', 15300022673, 90, 89, 67, 100, '小明']
sex, tel, score, name = tuple2
print(sex, name, score) # boy 小明 [90, 89, 67, 100]
(了解)
可以通過在列表或者元祖前加,來展開列表中的元素
tuple3 = (1, 2, 3, 4)
print(*tuple3) # 1 2 3 4
list1 = ['abc', 100, 200]
print(*list1) # abc 100 200
3.元祖的運算
+, *, ==, is, in, not in ---> 和列表一樣
print((1, 2, 3) + ('a','b')) #(1, 2, 3, 'a', 'b')
print((1, 2) * 3) # (1, 2, 1, 2, 1, 2)
print((1, 2, 3) == (1, 2, 3)) # True
print((1, 2, 3) is (1, 2, 3)) # False
print(1 in (1, 2, 3)) # True
print(1 not in (1, 2, 3)) # False
4.len(), max(), min()
tuple3 = 10, 230, 100, 78, 34
print(len(tuple3)) # 5
print(max(tuple3)) # 230
print(min(tuple3)) # 10
5.tuple()
所有的序列都可以轉換成元祖婚惫,注意,字典只能將key值作為元祖元素
print(tuple('abhdnc')) # ('a', 'b', 'h', 'd', 'n', 'c')
print(tuple([1, 23, 90])) # (1, 23, 90)
print(tuple(range(5))) # (0, 1, 2, 3, 4)
print(tuple({'a': 100, 'b': 200})) # ('a', 'b')
6.sorted()
可以通過sorted()方法魂爪,對元祖進行排序先舷,產生一個新的列表
tuple3 = 10, 230, 100, 78, 34
new = sorted(tuple3)
print(new, tuple3) # [10, 34, 78, 100, 230] (10, 230, 100, 78, 34)
tuple1 = (1, 'yue', True, [1, 2], lambda s:s*2)
print(tuple1) #(1, 'yue', True, [1, 2], <function <lambda> at 0x0000000001E83F28>)
三、認識字典
什么時候用容器類型的數據滓侍? ---> 需要同時保存多個數據的時候
什么時候用列表蒋川? ---> 保存的多個數據是同一類的數據(不需要區(qū)分)
什么時候用字典? ---> 保存的多個數據是不同類的數據 (需要區(qū)分)
1.什么是字典(dict)
字典是一個容器類的數據類型撩笆,可以用來存儲多個數據(以鍵值對的形式存儲)尔破。可變的浇衬,無序的
{key1:value1, key2:value2...}
可變 ---> 可以增刪改
無序 ---> 不能通過下標獲取值
鍵(key): 用來定位值的。要求只能是不可變的數據類 型(數字餐济,字符串耘擂,元祖...)。是唯一的
值(value): 存儲的數據絮姆∽碓可以是任何類型的數據
person1 = ['yuting', 18, 90, 100, '1547262889']
person2 = {'name': 'yuting', 'age': 18, 'face': 90,
'score': 100, 'tel': '1547262889', 'name':'小花'}
dict1 = {10: 893, 'abc': 100, (1, 23): 'abc'}
print(person2) # {'name': '小花', 'age': 18, 'face': 90,
# 'score': 100, 'tel': '1547262889'}
dict1 = {}
print(dict1) # {}
四秩霍、字典的增刪改查
1.查(獲取鍵值對的value)
獲取字典的值,必須通過key來獲取
a.字典[key] ---> 獲取key對應的值
注意:key值必須是存在的蚁阳,否則會報KeyError
student = {'name': '小明', 'age': 30, 'study_id': 'py001',
'sex': 'boy'}
print(student['name']) # 小明
print(student['sex']) # boy
b.字典.get(key) ---> 通過key獲取值
注意:key值不存在的時候不會報錯铃绒,結果是None
print(student.get('age'), student.get('study_id')) #30 py001
print(student.get('score')) # None
確定key一定存在就是使用[]語法,key可能不存在的時候使用get語法
c.直接遍歷字典(推薦使用)
通過for-in遍歷字典拿到的是key值
for x in student:
print(x, student[x])
d.其他遍歷方式(了解)
直接遍歷拿到值
for value in student.values():
print(value)
直接拿到key和value
print(student.items())
for key, value in student.items():
print(key, value)
2.增(添加鍵值對)
字典[key] = 值(key不存在)
car = {}
car['color'] = 'yellow'
print(car) # {'color': 'yellow'}
car['price'] = 300000
print(car) # {'color': 'yellow', 'price': 300000}
3.修改(修改值)
字典[key] = 新值 (key存在)
car['color'] = 'red'
print(car) # {'color': 'red', 'price': 300000}
4.刪 (刪除鍵值對)
a. del 字典[key] ---> 通過key刪除鍵值對
student = {'name': '小明', 'age': 30, 'study_id': 'py001',
'sex': 'boy'}
del student['age']
print(student)
# {'name': '小明', 'study_id': 'py001', 'sex': 'boy'}
b. 字典.pop(key) ---> 取出key對應的值(實質還是刪除key對應的鍵值對)
name = student.pop('name')
print(student, name)
# {'study_id': 'py001', 'sex': 'boy'} 小明
五螺捐、字典的相關操作
1.字典相關運算
==: 判斷兩個字典的值是否相等
is: 判斷兩個字典的地址是否相等
in 和 not in: key in 字典 / key not in 字典 ---> 判斷key是否存在
dic1 = {'a': 1, 'b': 2}
aa = dic1
print(dic1 is aa) T
print({'a': 100, 'b': 200} == {'b': 200, 'a': 100}) T
print({'a': 100, 'b': 200} is {'b': 200, 'a': 100}) F
print('abc' in {'abc': 100, 'a': 200}) T
print('abc' in {'100': 'abc', 'a': 200}) F
2.字典相關的函數和方法
len(字典) --> 獲取鍵值對的個數
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(len(dict1)) # 4
2.字典.clear() --> 清空字典
dict1.clear()
print(dict1) # {}
3.字典.copy() --> 將字典中的鍵值對復制一份產生一個新的字典
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict2 = dict1.copy()
print(dict2, dict1 is dict2)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4} False
4.dict.fromkeys(序列, 值) --> 創(chuàng)建一個字典颠悬,將序列中的每個元素作為key,值作為value
dict3 = dict.fromkeys('xyz', 100)
print(dict3) # {'x': 100, 'y': 100, 'z': 100}
dict3 = dict.fromkeys(['aa', 'bb', 'cc'], (1, 2))
print(dict3) # {'aa': (1, 2), 'bb': (1, 2), 'cc': (1, 2)}
字典.get(key) --> key不存在取None
字典.get(key,默認值) --> key不存在取默認值
student = {}
print(student.get('name')) # None
print(student.get('name', '無名')) # 無名
字典.values() --> 返回所有值對應的序列
字典.keys() --> 返回所有鍵對應的序列
字典.items() --> 將鍵值對轉換成元祖定血,作為一個序列的元素
注意:返回的都不是列表赔癌,是其他類型的序列
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
items = list(dict1.items())
print(items, type(items))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)] <class 'list'>
print(dict1.items(), type(dict1.items()))
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) <class 'dict_items'>
字典.setdefault(key) --> 添加鍵值對,鍵是key澜沟,值是None
字典.setdefault(key,value) --> 添加鍵值對灾票,鍵是key,值是value
注意:key存在的時候茫虽,對字典不會有任何操作(不會修改key對應的值)
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict1.setdefault('aa')
print(dict1)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'aa': None}
8.字典1.update(字典2) --> 使用字典2中鍵值對去更新字典1刊苍。(已經存在的key就更新,不存在就添加)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 200, 'c': 100}
dict1.update(dict2)
print(dict1) # {'a': 1, 'b': 200, 'c': 100}
六、集合
1.什么是集合(set)
容器,可以同時存儲多個數據,可變的速缨,無序的,元素是唯一的
可變 --> 增刪改
無序 --> 不能通過下標獲取元素
唯一 --> 自帶去重的功能
{元素1, 元素2...}
元素:只能是不可變的數據
set1 = {10, 20, 'abc', (10, 200), 10}
print(set1) # {(10, 200), 10, 20, 'abc'}
set2 = {} # 這個是空的字典
2.集合的增刪改查
a.查(獲取元素)
集合不能單獨的獲取一個元素螟蝙,也不能切片,只能通過for-in來遍歷
for x in set1:
print(x)
b.增(添加元素)
集合.add(元素) --> 在集合中添加一個元素
set1 = {1, 2, 3}
set1.add(4)
print(set1) # {1, 2, 3, 4}
集合1.update(序列) --> 將序列中的元素添加到集合1中
set1.update({'a', 'b'})
print(set1) # {'a', (10, 200), 20, 10, 'b', 'abc'}
set1.update('0987')
print(set1)
{10, 'b', 'abc', 20, '8', '7', (10, 200), 'a', '9', '0'}
set1.update(['abc', 'aaa'])
print(set1)
{10, 'b', 'abc', 20, '8', '7', (10, 200), 'aaa',
'a', '9', '0'}
set1.update({'name': 1, 'age': 18}) # 字典只添加key
print(set1)
{10, 'b', 'abc', 20, 'name', '8', 'age', '7',
(10, 200), 'aaa', 'a', '9', '0'}
3.刪(刪除元素)
集合.remove(元素) --> 刪除指定的元素
set1.remove(1)
print(set1) # {2, 3, 4}
4.改(集合不能改)
七救军、集合相關的數學運算
集合相關的運算: 是否包含,交集、并集莹妒、差集、補集
1.包含
集合1 >= 集合2 ---> 判斷集合1之中是否包含集合2
集合2 <= 集合2 ---> 判斷集合2之中是否包含集合1
set1 = {1, 2, 3, 4, 5, 10}
set2 = {3, 4, 1}
print(set1 >= set2) # T
2.交集 -> &
& --> 求兩個集合公共的部分
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3, 10, 20}
print(set1 & set2) # {1, 2, 3}
3.求并集
| --> 求兩個集合的和
print(set1 | set2) # {1, 2, 3, 4, 5, 10, 20}
4.求差集
集合1-集合2 --> 求集合1中除了集合2以外的部分
print(set1 - set2) # {4, 5}
5.求補集
^ --> 求兩個集合除了公共部分以外的部分
print(set1 ^ set2) # {20, 4, 5, 10}
八绰上、類型轉換
1.整型
int()
浮點數旨怠、布爾、部分字符串可以轉換成整型蜈块。
只有去掉引號后本身就是一個整數的字符串才能轉換成整型
print(int('34')) 34
print(int('+45')) 45
print(int('-90')) -90
print(int('34.5')) # ValueError
2.浮點數
整數鉴腻,布爾,部分字符串可以轉換成浮點數
去掉的引號百揭,本身就是一個數字的字符串才能轉換成浮點數
print(float(100)) # 100.0
print(float(True)) # 1.0
print(float('34.90')) # 34.90
print(float('100')) # 100.00
3.布爾
所有的數據都可以抓換成布爾值
為空為0的值轉換成False, 其他的數據都轉換成True
print(bool('abchd')) # True
print(bool('False')) # True
print(bool('')) # False
print(bool([1, 2, 3])) # True
print(bool([])) # False
print(bool({'a': 1})) # True
print(bool({})) # False
print(bool(())) # F
print(bool(0.00)) # F
print(bool(None)) # F
num = 100
if num == 0:
print('是0')
if not num:
print('是0')
names = [23]
if names:
print('不是空')
else:
print('是空')
num = 230
if num % 2:
print('是奇數') # 不是空
else:
print('是偶數') # 是偶數
4.字符串
str()
所有的數據都可以轉換成字符串
數據轉換成字符串爽哎,就是在數據的最外面加引號
print([str(100)])
print([str(True)])
print([str([1, 2, 3])])
print([str({'a': 1, 'b': 2})])
print([str(lambda x: x*2)])
list_str = str([1, 2, 3])
print(len(list_str))
5.列表
list()
序列才能轉換成列表。
將序列中的元素作為列表的元素器一。字典轉換成列表课锌,將字典的key作為列表的元素
print(list('styui'))
print(list((23, 45, 'ac')))
print(list({'a': 100, 'b': 89}))
print(list({'a': 100, 'b': 89}.items()))
6.元祖(和列表一樣)
tuple()
只能將序列轉換成元祖
print(tuple('ancbd'))
print(tuple({'a': 100, 'b': 89}))
7.字典
dict()
序列的每個元素有兩個元素的數據才能轉換成字典
list1 = [(1, 2)]
print(dict(list1))
tuple1 = ((1, 8), {'a', 'b'})
print(dict(tuple1))
8.集合
set()
序列可以轉換成集合,有去重的功能
print(set([1, 1, 90, 3, 10, 10]))
九、作業(yè)
用一個變量來保存一個班級的學生信息渺贤,學生信息包括:姓名雏胃、學號、成績(英語志鞍、體育瞭亮、美術、數學)固棚、年齡
b.給這個班級添加學生
c.根據姓名查看班級里的某個學生的信息
d.根據姓名刪除一個指定的學生信息
e.查看班級的所有的學生信息
f.求指定的學生平均成績
x = []
score = {}
name = input('請輸入你的姓名')
age = input('請輸入你的年齡')
number = input('請輸入你的學號')
scores['math'] = input('請輸入你的數學成績')
scores['English'] = input('請輸入你的英語成績')
scores['art'] = input('請輸入你的美術成績')
scores['sport'] = input('請輸入你的體育成績')