Python:将单个元素打印为字符串,并在列表中有多个元素时打印列表

我有以下字典(其中计数(值)反向排序):


sorted_dict={'A': 4, 'W': 4, 'T': 2, 'S': 2, 'I': 2, 'R': 1}

正如您所看到的,有 2 个键具有相同的值,即。A和W。


我编写了以下逻辑来获取最大计数


max_count = list(sorted_dict.values())[0]

max_count_letter_list = []

迭代字典中的每个键后,我将具有最大计数的字母添加到列表中。


for letter in sorted_dict:

    if sorted_dict[letter] == max_count:

        max_count_letter_list.append(letter) 

打印到控制台时,它被打印为列表,这正是我所期望的


print("Most frequent letter \"{}\" appears {} times"

          .format(max_count_letter_list, max_count))


Output: Most frequent letter "['W', 'A']" appears 4 times

但是,如果列表中有一个元素,它会像这样打印出来:


Most frequent letter "['A']" appears 4 times

我的期望是这样打印:Most frequent letter "A" appears 4 times


问题:在一行打印语句中,如何打印列表中不带括号的单个元素,如果它是一个列表,它应该打印元素列表。我需要写一个 if 语句还是有更好的方法来写这个?


一只名叫tom的猫
浏览 92回答 3
3回答

米脂

适合所有人的解决方案可能是用逗号连接项目print("Most frequent letter \"{}\" appears {} times".format(",".join(max_count_letter_list), max_count))# GivingMost frequent letter "A,W" appears 4 timesMost frequent letter "A" appears 4 times如果你想以不同的方式处理它们,你需要一个条件来分隔大小写: an if,然后正常编写或使用内联模式 # inlineprint("Most frequent letter \"{}\" appears {} times".format(letter_list[0] if len(letter_list) == 1 else letter_list, max_count))# multi-lineif len(letter_list) == 1:    print("Most frequent letter \"{}\" appears {} times".format(letter_list[0], max_count))else:    print("Most frequent letter \"{}\" appears {} times".format(letter_list, max_count))缩短前面代码的解决方案from itertools import groupbyfrom operator import itemgetterg = groupby(sorted_dict.items(), key=itemgetter(1))max_count, letter_list = next((count, [x[0] for x in vals]) for count, vals in g)

猛跑小猪

我认为这就是您正在考虑的...根据列表中的项目数量以不同方式打印的条件:max_count_letter_list = ['A', 'W']max_count = 4print("Most frequent letter \"{}\" appears {} times".format(max_count_letter_list[0] if len(max_count_letter_list) == 1 else max_count_letter_list, max_count))max_count_letter_list = ['A']print("Most frequent letter \"{}\" appears {} times".format(max_count_letter_list[0] if len(max_count_letter_list) == 1 else max_count_letter_list, max_count))结果:Most frequent letter "['A', 'W']" appears 4 timesMost frequent letter "A" appears 4 times

扬帆大鱼

print("Most frequent letter \"{}\" appears {} times".format((max_count_letter_list[0] if len(max_count_letter_list) ==1 else max_count_letter_list), max_count)我想这就是您正在寻找的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python