天天看點

python快速程式設計入門課本第六章_Python程式設計從入門到實踐 第六章-字典

6-1人 : 使用一個字典來存儲一個熟人的資訊, 包括名、 姓、 年齡和居住的城市。

該字典應包含鍵first_name 、 last_name 、 age 和city 。 将存儲在該字典中的每項資訊都列印出來。

6-2喜歡的數字 : 使用一個字典來存儲一些人喜歡的數字。 請想出5個人的名字, 并将這些名字用作字典中的鍵;

想出每個人喜歡的一個數字, 并将這些數字作為值存

儲在字典中。 列印每個人的名字和喜歡的數字。 為讓這個程式更有趣, 通過詢問朋友確定資料是真實的。

6-3詞彙表 : Python字典可用于模拟現實生活中的字典, 但為避免混淆, 我們将後者稱為詞彙表。

想出你在前面學過的5個程式設計詞彙, 将它們用作詞彙表中的鍵, 并将它們的含義作為值存儲在詞彙表中。

以整潔的方式列印每個詞彙及其含義。 為此, 你可以先列印詞彙, 在它後面加上一個冒号, 再列印詞彙的含義; 也可在一行列印詞彙,

再使用換行符(\n ) 插 入一個空行, 然後在下一行以縮進的方式列印詞彙的含義。

6-1

friend = {'first_name':'wu','last_name':'xiao','age':'18','city':'shihunjie'}print("my friend's name is" + friend['last_name'] + " "

+ friend['first_name'] + ",and his age is" + friend['age']+ ",he is from" + friend['city'] + ".")

輸出:

my friend's name is xiao wu ,and his age is 18,he is from shihunjie.

6-2 items() 函數作用:以清單傳回可周遊的(鍵, 值) 元組數組

names = {'a':1,'b':2,'c':3,'d':4,'e':5}for key,number innames.items():print(key + "'s favorite number is" + str(number))

6-3 我他媽氣死這麼兩行 items寫成iteams查了半天真是個憨批

names = {'del':'shanchu','print':'shuchu'}for name,act innames.items():print(name + ":")print(act)

輸出:

del :

shanchu

print :

shuchu

6-4 使用keys()和values()方法,懶得改了

6-5

river_country = {'nile':'Egypt','huanghe':'China','duonaohe':'Europe'}for name,country inriver_country.items():print("The" + name +"runs through" + country + ".")for name inriver_country.keys():print(name)for country inriver_country.values():print(country)

輸出:

The nileruns through Egypt.

The huangheruns through China.

The duonaoheruns through Europe.

nile

huanghe

duonaohe

Egypt

China

Europe

6-6 調查

names = {'a':1,'b':2,'c':3,'d':4,'e':5}

man= ['a','c','e','f']for name innames.keys():if name inman:print(name +", Thanks for accpet the survey.")elif name not inman:print(name+", We invite you to accpet the survey.")

輸出

a, Thanksforaccpet the survey.

b, We invite you to accpet the survey.

c, Thanksforaccpet the survey.

d, We invite you to accpet the survey.

e, Thanksfor accpet the survey.

6-7人:

a = {'first_name':'六花','last_name':'小鳥遊','age':'16','city':'中二病'}

b= {'first_name':'一護','last_name':'黑崎','age':'18','city':'死神'}

c= {'first_name':'大河','last_name':'逢坂','age':'20','city':'龍與虎'}

people=[a,b,c]for peoplee inpeople:print(peoplee)

輸出:

{'first_name': '六花', 'last_name': '小鳥遊', 'age': '16', 'city': '中二病'}

{'first_name': '一護', 'last_name': '黑崎', 'age': '18', 'city': '死神'}

{'first_name': '大河', 'last_name': '逢坂', 'age': '20', 'city': '龍與虎'}

6-8 後面就是字典中嵌套字典zzzz懶得寫了睡覺了明天再努力吧zzz