【发布时间】:2021-11-16 22:27:45
【问题描述】:
我正在尝试为一个练习编写一个脚本,该脚本允许我对字符串中的字符进行排序并计算出现次数最多的字符,但我似乎无法以字符串的形式打印出结果作为它的一个元组。任何人对我如何做到这一点有任何想法将不胜感激。
import sys
stringInput = (sys.argv[1]).lower()
stringInput = sorted(stringInput)
DictCount = {}
Dictionary = {}
def ListDict(tup, DictStr):
DictStr = dict(tup)
return DictStr
for chars in stringInput:
if chars in Dictionary:
Dictionary[chars] += 1
else:
Dictionary[chars] = 1
ListChar = sorted(Dictionary.items(), reverse=True, key=lambda x: x[1])
Characters = (ListChar[0], ListChar[1], ListChar[2], ListChar[3], ListChar[4])
print(ListDict(Characters, DictCount))
当前输出:
python3 CountPopularChars.py sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS
{'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
想要的输出:
d:7,s:7,e:6,j:4,w:3
【问题讨论】:
-
请用当前的实际输出以及您想要的输出更新您的问题。
-
只是循环和打印项目,而不是尝试打印字典的表示
-
目前我尝试循环和打印 for i in range(5): print(*ListChar[i], sep=':', end=",") 但是它的输出有一个 , % 结尾
-
btw
DictCount在您的代码中没有任何作用,应该被删除。
标签: python python-3.x python-2.7 dictionary