我正在嘗試為練習撰寫一個腳本,該腳本允許我整理字串中的字符并計算重復出現的最高字符,但我似乎無法以字串的形式將結果列印為元組。任何人對我如何做到這一點有任何想法將不勝感激。
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
uj5u.com熱心網友回復:
以這種方式創建您的輸出:
output = ','.join(f"{k}:{v}" for k, v in ListChar)
print(output)
輸出:
e:17,d:7,a:3,b:1,c:1
uj5u.com熱心網友回復:
嘗試:
yourDict = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
print(','.join("{}:{}".format(k, v) for k, v in yourDict.items()))
輸出:
d:7,s:7,e:6,j:4,w:3
uj5u.com熱心網友回復:
要不就:
>>> dct = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
>>> ','.join(f'{k}:{v}' for k,v in dct.items())
'd:7,s:7,e:6,j:4,w:3'
uj5u.com熱心網友回復:
您的代碼是高度冗余的。您可以使用collections.Counter幫助以更簡潔的方式撰寫它:
from collections import Counter
# Hard coded stringInput for ease in this test
stringInput = 'sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS'.lower()
c = Counter(stringInput)
ListChar = sorted(c.items(), reverse=True, key=lambda x: x[1])
print(','.join(f"{k}:{v}" for k, v in ListChar[:5]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/312290.html
標籤:Python 蟒蛇-3.x python-2.7 字典
