我想創建一個字典,以字串中出現的字母作為鍵,并將出現多次的字母作為值。
我想要的帶有示例“出現”的輸出應如下所示:
{1: ['o', 'u', 'n'], 3: ['c'], 2: ['r', 'e']}
現在它看起來像這樣:
{1: ['o', 'u', 'n'], 3: ['c', 'c', 'c'], 2: ['r', 'r', 'e', 'e']}
我現在的代碼:
letters = list(text)
new_dict = {}
for elements in list(text):
if letters.count(elements) not in new_dict:
new_dict[letters.count(elements)] = [elements]
else:
new_dict[letters.count(elements)].append(elements)
return new_dict
uj5u.com熱心網友回復:
檢查這封信是否已經在字典中,并且只有在沒有添加它的情況下:
letters = list(text) # this line is not needed
new_dict = {}
for elements in list(text): # `for elements in text:` works just fine
if letters.count(elements) not in new_dict: # text.count(...) works just like letters.count(...)
new_dict[letters.count(elements)] = [elements]
else: # can be simpified to `elif elements not in new_dict[...]:`
if elements not in new_dict[letters.count(elements)]: # check if the character is already present
new_dict[letters.count(elements)].append(elements)
return new_dict
順便提一句。您不必將字串轉換為串列即可迭代,支持成員資格測驗(a 中的 b)或具有count方法。
所有這些也適用于字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350546.html
下一篇:刮取后如何將值存盤在一起
