Python核心程式設計 練習 第七章

2021-06-26 14:28:44 字數 2908 閱讀 1632

#7–1. 字典方法。哪個字典方法可以用來把兩個字典合併到一起?

#可以通過update來更新。

>>> dict1 =

>>> dict2 =

>>> dict1.update(dict2)

>>> dict1

>>>

#7–3. 字典和列表的方法。 

#(a) 建立乙個字典,並把這個字典中的鍵按照字母順序顯示出來。

#(b) 現在根據已按照字母順序排序好的鍵,顯示出這個字典中的鍵和值。

#(c)同(b),但這次是根據已按照字母順序排序好的字典的值,顯示出這個字典中的鍵和值。

#!/usr/bin/env python

#-*- coding:utf-8 -*-

dict1 =

for i in sorted(dict1):

print "key:", i," and value:", dict1[i]

for value in sorted(dict1.values()):

for key in dict1.keys():

if dict1[key] == value:

print "key:", key, "and value:", value

#7-4. 建立字典。給定兩個長度相同的列表,比如說,列表[1, 2, 3,...]和['abc', 'def','ghi',...],用這兩個列表裡的所有資料組成乙個字典,像這樣:

#!/usr/bin/env python

#-*- coding:utf-8 -*-

dict1 = {}

keys = [1, 2, 3, 4, 5, 6]

values = ["hello", "world", "i", "love", "my", "python"]

for i in range(len(keys)):

dict1[keys[i]] = values[i]

print dict1

#7-7. 顛倒字典中的鍵和值。用乙個字典做輸入,輸出另乙個字典,用前者的鍵做值,前者的值做鍵。

#!/usr/bin/env python

#-*- coding:utf-8 -*-

dict1 =

dict2 = {}

for key,value in dict1.items():

dict2[value] = key

print dict1

print dict2

#7-8. 人力資源。建立乙個簡單的雇員姓名和編號的程式。讓使用者輸入一組雇員姓名和編號。你的程式可以提供按照姓名排序輸出的功能,雇員姓名顯示在前面,後面是對應的雇員編號。附加題:新增一項功能,按照雇員編號的順序輸出資料。

#!/usr/bin/env python

#-*- coding:utf-8 -*-

def dit():

dict1 = {}

while true:

inf = raw_input("請輸入姓名和編號,格式(姓名:編號)(q結束):")

if inf == "q":

break

num = inf.split(":")

dict1[num[0]] = num[1]

for key in sorted(dict1.keys()):

print "姓名:%s,編號:%s" %(key, dict1[key])

for value in sorted(dict1.values()):

for key in dict1.keys():

if dict1[key] == value:

print "編號:%s,姓名:%s" % (key, value)

dit()

#7–10. 加密。 

(a) 用上乙個練習的思路編寫乙個"rot13"翻譯器。"rot13"是乙個古老而又簡單的加密方法,它把字母表中的每個字母用其後的第13 個字母來代替。字母表中前半部分字母將被對映到後半部分,而後半部分字母將被對映到前半部分,大小寫保持不變。舉例來說,'a'將被替換為'n','x'將被替換為'k'; 數字和符號不進行翻譯。

#!/usr/bin/env python

#-*- coding:utf-8 -*-

import string

numlower = ""

numupper = ""

numlower = string.lowercase * 2

numupper = string.uppercase * 2

def code_rot13(strtemp):

newstring = ""

for i in strtemp:

if i.islower():

newstring += numlower[numlower.find(i) + 13]

else:

newstring += numupper[numupper.find(i) + 13]

return newstring

if __name__ == '__main__':

while true:

string = raw_input("please enter the string(-1 to quit):")

if string == '-1':

break

print "the code rot13 is:", code_rot13(string)

print "the decode rot13 is", code_rot13(code_rot13(string))

《python核心程式設計 第七章字典》

0 python字典是容器型別,鍵可以是可以雜湊的各種型別 列表和字典不是可雜湊的所以他們不行 通常用字串作為key的比較多 a a 1 dict 可以用工廠方法來建立字典 dict x 1 y 2 2 fromkeys 內建方法建立字典,字典中的元素具有相同的值 fromkeys x y 1 3 ...

python第七章 python教程(第七章)

字典和集合 字典是python中唯一,乙個對映型別 如何建立乙個字典,如下 dict dict 滲透 網路安全 怎麼理解字典呢?現實生活中的字典可以通過首字母進行查詢要查詢的漢子,python也可以這樣理解,通過 前的元素查詢到冒號後的元素。為什麼說字典是唯一乙個對映型別呢?看圖。對映型別區別與序列...

python入門練習第七章7 1 7 10

僅作練習記錄,如有錯誤歡迎指正。7 1 汽車租賃 編寫乙個程式,詢問使用者要租賃什麼樣的汽車,並列印一條訊息,如 let me see if i can find you a subaru car input what kind of car would you like to rent?print...