使用for循环打印字典项一次,而不重复列出的每个项目的打印功能

时间:2018-01-04 00:43:34

标签: python python-3.x list dictionary printing

我是Python和Stackoverflow的新手,所以很抱歉,如果我的格式很糟糕。但是我创建了这个字典并为其分配了列表中包含的键和值。这是我的代码目前的样子:

favorite_languages = {
   'jen': ['python', 'ruby'],
   'sarah': ['c'],
   'edward': ['ruby', 'go'],
   'phil': ['python', 'haskell'],
}


for name, languages in favorite_languages.items():
   for language in languages:
        if len(languages) >= 2:
            print("\n" + name.title() + "'s favorite languages are:" +
                  language.title())
        elif len(languages) == 1:
            print(name.title() + "'s favorite language is: " +
                  language.title())

运行时代码的结果如下所示:

Sarah's favorite language is: C
Edward's favorite languages are:Ruby
Edward's favorite languages are:Go
Jen's favorite languages are:Python
Jen's favorite languages are:Ruby
Phil's favorite languages are:Python
Phil's favorite languages are:Haskell

但我只希望它为每个键重复一次句子,同时在每个句子中包含相应的值。像这样:

Sarah's favorite language is: C
Edward's favorite languages are:Ruby, Go
Jen's favorite languages are:Python, Ruby
Phil's favorite languages are:Python, Haskell

2 个答案:

答案 0 :(得分:4)

您可以尝试类似

的内容
for name, languages in favorite_languages.items():
     print("{}'s favorite language{} : {}".format(
             name.title(),
             "s are" if len(languages) > 1  else " is",
             ", ".join(languages))
     )

答案 1 :(得分:3)

您不希望在循环中迭代语言。这里应该使用string.join

for name, languages in favorite_languages.items():
    be = ' is: ' if len(languages) == 1 else 's are: '
    print(name.title() + '\'s favorite language' + be + ', '.join(languages))