python - 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?
解决方案
适合所有人的解决方案可能是用逗号连接项目
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)
推荐阅读
- c++ - 了解函数类型
- java - 如何强制将特定日期值放入时间戳?
- sql - 保存 .sql 文件与创建视图
- node.js - 如何从网站解析有关某些产品的信息(使用 node.js)?
- python - 摆脱选项菜单周围的白色边框
- angular - 如何在表格列中使用 ng2-dragula
- html - 物化工具提示卡在页面顶部
- openshift - Chaos Toolkit 是否支持基于 CRI-O 的运行时?例如它可以在 OpenShift Container Platform v4.3 上运行吗?
- c++ - glUniform() 的无效位置试图做点阴影
- nginx - nginx - 如何使用 stub_status 创建 /status