6-5 河流:創建一個字典,在其中存儲三條大河流及其流經的國家。其中一個鍵—值對可能是’nile’: ‘egypt’ 。
- 使用循環爲每條河流打印一條消息,如“The Nile runs through Egypt.”。
- 使用循環將該字典中每條河流的名字都打印出來。
- 使用循環將該字典包含的每個國家的名字都打印出來。
Solution:
Rivers = {'nile': 'egypt', 'amazom': 'brazil', 'yangtze': 'china'}
for name, country in Rivers.items():
print("The " + name.title() + " runs through " + country.title() + ".")
for name in Rivers.keys():
print(name.title(), end = ' ')
print()
for country in set(Rivers.values()):
print(country.title(), end = ' ')
print()
Output:
The Nile runs through Egypt.
The Amazom runs through Brazil.
The Yangtze runs through China.
Nile Amazom Yangtze
Brazil Egypt China
6-6 調查:在6.3.1節編寫的程序favorite_languages.py中執行以下操作。
- 創建一個應該會接受調查的人員名單,其中有些人已包含在字典中,而其他人未包含在字典中。
- 遍歷這個人員名單,對於已參與調查的人,打印一條消息表示感謝。對於還未參與調查的人,打印一條消息邀請他參與調查。
Solution:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'
}
test_people = ['jen', 'tim', 'phil', 'faker']
for test_person in test_people:
if test_person in favorite_languages.keys():
print("Thank you, " + test_person.title() + "!")
else:
print("Please take part in the test, " + test_person.title() + ".")
Output:
Thank you, Jen!
Please take part in the test, Tim.
Thank you, Phil!
Please take part in the test, Faker.
6-11 城市:創建一個名爲cities 的字典,其中將三個城市名用作鍵;對於每座城市,都創建一個字典,並在其中包含該城市所屬的國家、人口約數以及一個有關該城市的事實。在表示每座城市的字典中,應包含country 、population和fact等鍵。將每座城市的名字以及有關它們的信息都打印出來。
Solution;
beijing_data = {
'country': 'China',
'population': '21730000',
'fact': 'Capital of China.'
}
tokyo_data = {
'country': 'Japan',
'population': '37000000',
'fact': 'Capital of Japan.'
}
paris_data = {
'country': 'France',
'population': '11000000',
'fact': 'Capital of France.'
}
cities = {
"beijing": beijing_data,
"tokyo": tokyo_data,
"paris": paris_data
}
for city, data in cities.items():
print(city.title() + ":")
for title, content in data.items():
print('\t' + title.ljust(10, ' ') + '\t:' + '\t' + content)
print()
Output:
Beijing:
country : China
population : 21730000
fact : Capital of China.
Tokyo:
country : Japan
population : 37000000
fact : Capital of Japan.
Paris:
country : France
population : 11000000
fact : Capital of France.
注:字符串的ljust方法可以將字符串用需要的字符自動補成想要的長度,並將字符保存在這個補成字符串的左端,rjust方法則是將其保存在字符串的右端。用法爲str.ljust/rjust(length, char)