大学python教材实验七字典与集合答案_2018-08-28 day7 python基础 字典和集合(含作业)...
1.字典(dict)
一.字典是容器類型(序列 ),以鍵值對作為元素。字典里面存的數據全是以鍵值對的形式出現的
b/鍵值對----> 鍵:值(key:value)
dict1 = {'key1':value1,'key2':value2 }
ditc2 = {} #空的字典
'''
鍵(key):要唯一,不可變的(字符串,數字,布爾,元組---->推薦使用字符串)
值(value):可以不唯一,可以是任何類型的數據。
'''
A.字典是可變的(增刪改查) ----->可指的是字典中的鍵值對的值和個數可變
1.獲取字典的元素對應的值(字典存數據,實質還是存的value,key是獲取vlaue的手段)。(查)
'''
(—)
value = 字典 [key] #key不存在會報錯KeyError
dict1 = {'key1':value1,'key2':value2 }
value1 = dict1 ['key1']
'''
'''
(二)
dict1 = {'key1':value1,'key2':value2 }
print(dict1.get(key1)) # 結果是value1
如果key1不存在,返回None.
'''
'''
總結:
a.確定key肯定存在的時候用 dict['key]'獲取value
b.不確定key是否存在,不存在的時候不希望報錯,而是想要自己對它進行特殊處理的時候使用dict.get('key')
'''
2.遍歷字典(直接取到的是字典的所有key值)
'''
person = {'name':'txf','age':18,'grade':90}
for x in person:
print(x,end=' ')
結果:name age grade
'''
B.改(修改key對應的value)
'''
字典 [key] = 新值 #key是存在的
'''
C.增加(添加鍵值對)
'''
字典 [key] =值 #key不存在的
注意:
當key是存在的時候,表達修改,如果key不存在則表示添加。
'''
D.刪(刪除鍵值對)
'''
一
del 字典[key] #刪除鍵值對
二
字典.pop(key) #和list的用法差不多是拿出來。
'''
二:字典相關操作
a.
'''
a.字典不支持 '+' 和 '*'
b.字典支持 in 和 not in (判斷key是否存在)
c.字典支持len()
'''
b.相關的方法
1.字典.copy()
'''
拷貝字典中的所有的元素,放到一個新的字典中。
'''
'''
dict1 = {'a':1,'b':2}
dict2 = dict1 #將dict1中的地址賦給對dict2,兩個變量指向同一個地址
dict3 = dict1.copy() #將dict1中的內容復制到一個新的內存區域,然后將新的地址給dict3
'''
2.dict.fromkeys(序列,默認值=None)
'''
a.將序列中的每個值作為key,默認值為value創建一個新的字典
b.注意:默認值可以不寫,寫的話只能寫一個值
dict1 = dict.fromkeys('abcdefg','txf')
print(dict1)
{'a': 'txf', 'b': 'txf', 'c': 'txf', 'd': 'txf', 'e': 'txf', 'f': 'txf', 'g': 'txf'}
'''
3.字典.keys() #獲取字典中的所有的key,以dict_keys的形式返回(可以遍歷 類似list)
dict1 = {'a': 'txf', 'b': 'txf', 'c': 'txf', 'd': 'txf', 'e': 'txf', 'f': 'txf', 'g': 'txf'}
print(dict1.keys(),type(dict1.keys))
結果:
dict_keys(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
4.字典.value() #和 字典.keys() 類似 是獲取字典中的所有的value。
5.字典.items() #獲取key,value以元組的形式返回(不推薦使用,消耗CPU)。
dict1 = {'a': 'txf', 'b': 'txf', 'c': 'txf', 'd': 'txf', 'e': 'txf', 'f': 'txf', 'g': 'txf'}
print(dict1.items())
for k ,v in dict1.items():
print(k,v,end=' ')
'''
dict_items([('a', 'txf'), ('b', 'txf'), ('c', 'txf'), ('d', 'txf'), ('e', 'txf'), ('f', 'txf'), ('g', 'txf')])
a txf b txf c txf d txf e txf f txf g txf
'''
6.字典.setdefault(key,默認值=None) #給字典添加鍵值對,如果key存在,則不會生效
dict1 = {'a': 'txf', 'b': 'txf', 'c': 'txf'}
dict1.setdefault('ab',123)
print(dict1)
'''
{'a': 'txf', 'b': 'txf', 'c': 'txf', 'ab': 123}
'''
7.字典1.update(字典2) #將字典2中的鍵值對更新到字典1中。更新方式:如果字典2的key,在字典1中是存在的,就字典2中的值取更新字典1中的值,如果不存在就添加到字典1中、
dict1 = {'a': 'txf', 'b': 'txf', 'c': 'txf'}
dict2 = {1:1,2:2}
dict2.update(dict1)
print(dict2)
'''
{1: 1, 2: 2, 'a': 'txf', 'b': 'txf', 'c': 'txf'}
'''
字典相關函數.png
2 列表和字典的組合使用
1.什么時候用列表,什么時候用字典
'''
a.保存的多個數據的類型是同一個類型的時候,用列表
b.保存的多個數據的類型不同,就使用字典。
'''
2.字典里面可以有list,list里面也可以有字典
a ={1:[1,2],2:[2,3]}
b =[{1,2,3},4,4]
student_system = {'class_name':'python1806',
'students':[
{'name':'student1','age':21,'id':'001'},
{'name':'student2','age':22,'id':'002'},
{'name':'student3','age':23,'id':'002'}
]
}
'''
22
'''
'''
#學生管理系統
# 1.一個系統可以存儲多個學生
# # 2.一個學生可以存儲:姓名,電話,籍貫,專業,學號等等
# # 3.添加學生
# # 4.刪除學生
# # 5.修改學生的信息
student_system = {'class_name':'python1806',
'students':[
{'name':'student1','age':21,'id':'001'},
{'name':'student2','age':22,'id':'002'},
{'name':'student3','age':23,'id':'003'}
]
}
print(student_system['students'][1]['age']) # 打出這個 22
student_system['students'][1]['name'] = 'txf' # 把student2變成txf
# 添加一個學生信息
dict1 = {'name': 'student4','age': 24,'id': '004'}
student_system['students'].append(dict1)
#刪除學生信息
user_input = input('請輸入學生的姓名:')
for x in student_system['students'][:]:
if x['name'] == user_input:
student_system['students'].remove(x)
else:
print('系統沒得這個人的,請重新輸入:')
print(student_system)
'''
3.集合(set)
集合是python中的一種類型:無序的,可變的,值是唯一的
a.聲明一個集合
'''
set1 = {1,2,3,4,5,'abc',True}
print(set1,type(set1)
set2 = set('asakjdhksawawda') #將其他的序列轉換成集合,自帶一個去重的功能
print(set2)
{1, 2, 3, 4, 5, 'abc'}
{'a', 'k', 'h', 's', 'j', 'w', 'd'}
'''
'''
注意:除了容器類型,其他的基本都可以(數字,布爾和字符串是可以的)
'''
b.集合里面的操作
A.獲取元素(集合是不能單獨獲取其中的某一個元素的)只能遍歷獲取每個元素(查)
'''
for x in set3:
print(x)
'''
B.增(添加元素)
1.集合.add('good')
'''
set3.add(12)
set3.add('wda')
'''
2.集合1.update(集合2) # 將集合2的元素添加到集合1(有過濾的)
'''
set3.update()
'''
3.刪
集合.remove()
'''
set3.remove()
set3.clear() #全部刪 結果是-----> set()
'''
C.數學相關的集合運算
'''
a.判斷包含情況:
集合1 >=集合2 #判斷集合1是否包含集合2
集合1 <= 集合2 # 判斷集合2是否包含集合1
b.求并集: |
集合1 | 集合2 #求并集
c.求交集:&
集合1 & 集合2 #求交集
d.求差集: -
集合1 - 集合2 #求差集
e.求補集:^
集合1-集合2 #集合1和集合2除了公共部分剩下的
'''
作業
作業.png
number_id = 0
student_message = {str(number_id):['stu1','男',123,'吃']}
def add_student(n,message_list):
user_name = input('請輸入你的名字:')
user_sex = input('請輸入你的性別:')
user_tel = input('請輸入你的電話:')
user_hobby = input('請輸入你的愛好:')
str1 = str(n)
message_list[str1] = [user_name,user_sex,user_tel,user_hobby]
def select_student(message_list):
user_input = input('請輸入姓名或者學號:')
print_count = []
if user_input.isdigit():
user_message = message_list[user_input]
print(user_message)
print('姓名:%s' % user_message[0],end=' ')
print('學號:%s' % user_input)
print('性別:%s' % user_message[1],end=' ')
print('電話:%s' % user_message[2],end=' ')
print('愛好:%s' % user_message[3])
elif user_input.isalpha():
message_dict = message_list.values()
for x in message_dict:
for y in x:
if y == user_input:
for id in message_list:
if message_list[id][0] == user_input:
print_count.append(id)
if print_count.count(id) <= 1:
print('姓名:%s' % user_input,end=' ')
print('學號:%s' % id,end=' ')
print('性別:%s' % message_list[id][1],end=' ')
print('電話:%s' % message_list[id][2], end=' ')
print('愛好:%s' % message_list[id][3])
else:
print('請重新輸入')
select_student(message_list)
def del_student(message):
user_input = input('請輸入想刪除的姓名或者id:')
if user_input.isdigit():
message.pop(user_input)
else:
count = 1
print_count = []
message_dict = message.values()
for x in message_dict:
for y in x:
if y == user_input:
for id in message:
if message[id][0] == user_input:
print_count.append(id)
a = {id: [y,message[id][1],message[id][2],message[id][3]],count:'None'}
if print_count.count(id) <= 1:
print(count,' ',end=' ')
print('姓名:%s 學號:%s 性別:%s 電話:%s 愛好:%s' % (a[id][0],id,a[id][1],a[id][2],a[id][3]))
print(' ')
count += 1
else:
print("輸入錯誤")
del_student(message)
else:
user_select = input('請輸入想刪除的選項:')
message.pop(user_select)
# return (message)
def select_all_student(student_message):
for dict_info in student_message:
message = student_message[dict_info]
print('姓名:%s 學號:%s 性別:%s 電話:%s 愛好:%s' % (message[0],dict_info,message[1],message[2],message[3]))
def update_student(student_message):
user_input1 = input('請輸入你的id:')
user_input2 = input('請輸入想修改的序號:1-姓名,2-性別,3-電話,4-愛好:請輸入對應的數字:')
user_input3 = input('請輸入新的內容:')
student_message[user_input1][int(user_input2)] = user_input3
def main(number_id):
while True:
print('==================================================')
print(' ' * 8 + '學生管理系統' + '')
print('1.添加學生')
print('2.查看學生')
print('3.刪除學生')
print('4.查看所有學生信息(管理員)')
print('5.修改學生信息')
print('6.退出')
print('==================================================')
user_input1 = input('請輸入想輸入的:')
if not user_input1.isdigit():
print('請輸入對應的數字:數字!!!!')
else:
user_input = int(user_input1)
if user_input ==6:
break
elif user_input == 1:
add_student(number_id+1,student_message)
number_id += 1
elif user_input == 2:
select_student(student_message)
elif user_input == 3:
del_student(student_message)
elif user_input == 5:
update_student(student_message)
elif user_input == 4:
a = input('請輸入管理員姓名:')
b = input('請輸入管理密碼:')
if a == 'stu1' and b == 'stu1':
select_all_student(student_message)
else:
print('輸入錯誤,請重新輸入')
else:
print('還沒得這個功能的-----')
if __name__ == '__main__':
main(number_id)
'''
OK
'''
總結
以上是生活随笔為你收集整理的大学python教材实验七字典与集合答案_2018-08-28 day7 python基础 字典和集合(含作业)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue 项目引用static目录资源_v
- 下一篇: java 8u111 8u112_JDK