首页 > 解决方案 > Python: Printing a single element as a string and printing a list when there are multiple elements in list

问题描述

I have the following dictionary (where the counts (values) are sorted in reverse):

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

As you can see there are 2 keys with the same values ie. A and W.

I have written the the follow logic to get the max count

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

After iterating through each key in the dictionary, I add the letters with max counts to the list.

for letter in sorted_dict:
    if sorted_dict[letter] == max_count:
        max_count_letter_list.append(letter) 

When printing to the console, it is printed as a list which is what I expect

print("Most frequent letter \"{}\" appears {} times"
          .format(max_count_letter_list, max_count))

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

However, if I have a single element in the list, it prints out like this:

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

My expectation is to print like this: Most frequent letter "A" appears 4 times

Question: In the one line print statement, how do I print just a single element from the list without the brackets and if it is a list, it should print the list of elements. Do I need to write a if statement or is there a better way to write this?

标签: python

解决方案


适合所有人的解决方案可能是用逗号连接项目

print("Most frequent letter \"{}\" appears {} times".format(",".join(max_count_letter_list), max_count))

# Giving
Most frequent letter "A,W" appears 4 times
Most frequent letter "A" appears 4 times

如果您想以不同的方式处理它们,则需要一个条件来分隔案例:an if,然后正常编写或使用内联模式

 # inline
print("Most frequent letter \"{}\" appears {} times".format(letter_list[0] if len(letter_list) == 1 else letter_list, max_count))

# multi-line
if 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 groupby
from operator import itemgetter
g = groupby(sorted_dict.items(), key=itemgetter(1))
max_count, letter_list = next((count, [x[0] for x in vals]) for count, vals in g)

推荐阅读