在使用字典循环时,我想要包含一个if语句来检查开发人员是否有多个喜欢的语言并将语句修改为复数。有人可以帮助解决这个问题吗?
favorite_languages = {
'jen': ['python','ruby']
'sarah': ['c'],
'edward': ['ruby','C++'],
'phil': ['python'],
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
答案 0 :(得分:1)
添加if
声明:
favorite_languages = {
'jen': ['python', 'ruby'], # forgot comma here
'sarah': ['c'],
'edward': ['ruby', 'C++'],
'phil': ['python'],
}
for name, languages in favorite_languages.items(): # lost indentation here
if len(languages) > 1:
print('{}\'s favorite languages are {}.'.format(name.title(), ", ".join(languages)))
else:
print('{}\'s favorite language is {}.'.format(
name.title(),
languages[0].title(),
))
答案 1 :(得分:1)
以下是使用str.format
的一种方式。
favorite_languages = {'jen': ['python','ruby'],
'sarah': ['c'],
'edward': ['ruby','C++'],
'phil': ['python']}
for name, language in favorite_languages.items():
print("{0}'s favorite language{1} {2}".format(name.title(),
's are' if len(language)>1 else ' is', ' and '.join(language)))
结果:
Jen's favorite languages are python and ruby
Sarah's favorite language is c
Edward's favorite languages are ruby and C++
Phil's favorite language is python
答案 2 :(得分:-1)
这就是你想要的:
print('{}\'s favorite ' +('language is' if len(language.title()==1) else'languages are')+ '{}.'.format(
我写了这么快,我不知道字典是如何工作的,所以如果这不正确,请告诉我。