3 回答
TA贡献1836条经验 获得超3个赞
适合所有人的解决方案可能是用逗号连接项目
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)
TA贡献1858条经验 获得超8个赞
我认为这就是您正在考虑的...根据列表中的项目数量以不同方式打印的条件:
max_count_letter_list = ['A', 'W']
max_count = 4
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))
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 times
Most frequent letter "A" appears 4 times
TA贡献1799条经验 获得超9个赞
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)
我想这就是您正在寻找的。
添加回答
举报