马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
favorite_places = {
"Tom":["Changsha","Chengdu"],
"Joe":["Hangzhou","Chongqing","Kashi"],
"Jerry":["Tianjin"],
}
for name,cities in favorite_places.items():
if len(cities) > 1:
print(f"{name}'s favorite places are:")
for city in cities:
print(city)
else:
print(f"{name}'s favorite places is {cities}.")
这段代码得到的结果是:
Tom's favorite places are:
Changsha
Chengdu
Joe's favorite places are:
Hangzhou
Chongqing
Kashi
Jerry's favorite places is ['Tianjin'].
请问如何修改能使最后一行变为 Jerry's favorite places is Tianjin.
我试过这样可以,但不知道有没有更简洁的方法?favorite_places = {
"Tom":["Changsha","Chengdu"],
"Joe":["Hangzhou","Chongqing","Kashi"],
"Jerry":["Tianjin"],
}
for name,cities in favorite_places.items():
if len(cities) > 1:
print(f"{name}'s favorite places are:")
for city in cities:
print(city)
else:
for city in cities:
print(f"{name}'s favorite places is {city}.")
print(f"{name}'s favorite places is {cities[0]}.")
这样呢
|