高级编程技术(Python)作业6

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)

猜你喜欢

转载自blog.csdn.net/weixin_38311046/article/details/79680890