选做的题目:练习6-9、练习6-11。
练习6-9:喜欢的地方
创建一个名为favorite_places的字典。在这个字典中,将三个人的名字用作键,并存储每个人喜欢的1~3个地方。为了让这个练习更有趣些,可以让一些朋友说出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
代码1:
favorite_places = {
'Alice':['Beijing', 'Tianjin', 'Shanghai'],
'Betty':['Guangzhou'],
'Cathy':['Suzhou', 'Hangzhou']
}
for name,place in favorite_places.items():
print(f'{name}\'s favorite city: ')
if len(place) == 1:
print(f'\t{place[0]}')
else:
for the_place in place:
print(f'\t{the_place}')
运行结果:
Alice's favorite city:
Beijing
Tianjin
Shanghai
Betty's favorite city:
Guangzhou
Cathy's favorite city:
Suzhou
Hangzhou
代码2:
使用if语句,将len(place)得到的元素个数作为判断条件。
(注意:这里我的代码会重复输出’somebody‘s favorite city is xxx。)
favorite_places = {
'Alice': ['Beijing', 'Tianjin', 'Shanghai'],
'Betty': ['Guangzhou'],
'Cathy': ['Suzhou', 'Hangzhou']
}
for name,place in favorite_places.items():
if len(place) == 1:
print(f'{name}\'s favorite place is {place[0]}. ')
else:
for the_place in place:
print(f'{name}\'s favorite place is {the_place}. ')
运行结果:
Alice's favorite place is Beijing.
Alice's favorite place is Tianjin.
Alice's favorite place is Shanghai.
Betty's favorite place is Guangzhou.
Cathy's favorite place is Suzhou.
Cathy's favorite place is Hangzhou.
练习6-11:城市
创建一个名为cities的字典,将三个城市名用作键。对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country、population和fact等键。将每座城市的名字以及有关信息都打印出来。
代码1:
cities = {
'Beijing': {
'country': 'China',
'population': '1_000_000', # 随便打的数
'fact': 'ancient'},
'Tokyo': {
'country': 'Japan',
'population': '1_000_000',
'fact': 'capital'}
}
for name, information in cities.items():
print(f'{name}: ')
print (f"\tcountry: {information['country']}")
print (f"\tpopulation: {information['population']}")
print (f"\tfact: {information['fact']}")
# OR
for name, information in cities.items():
print(f'{name}:')
country = information['country']
population = information['population']
fact = information['fact']
print(f'\tcountry: {country}')
print(f'\tpopulation: {population}')
print(f'\tfact: {fact}')
运行结果:
Beijing:
country: China
population: 1_000_000
fact: ancient
Tokyo:
country: Japan
population: 1_000_000
fact: capital
代码2:
cities = {
'Beijing': {
'country': ['China'],
'population': ['1_000_000'],
'fact': ['ancient']},
'Tokyo': {
'country': ['Japan'],
'population': ['1_000_000'],
'fact': ['capital']}
}
for name, information in cities.items():
print(f'{name}: ')
for country in information['country']:
print (f'\tcountry: {country}')
for population in information['population']:
print (f'\tpopulation: {population}')
for fact in information['fact']:
print(f'\tfact: {fact}')
如果“fact”里有很多值,可以使用列表的形式。虽然这个字典里只有一个值,但还是写一下吧。
运行结果:
Beijing:
country: China
population: 1_000_000
fact: ancient
Tokyo:
country: Japan
population: 1_000_000
fact: capital