[英]How to create a new key in dictionary with value from another key list from a list of dictionary in Python?
[英]How to create a dictionary from existing list? Key Value must be the amount of repeats for that key
我正在嘗試創建一個“最想要的字母”程序,該程序將字符串作為輸入,輸出應該是該字符串中最重復的字母。 目前,我不知道如何創建字典(例如dict.items():[("a", 2), ("b", 5)...]
)。
def checkio(text: str) -> str:
input_text = text
lowercase_input = str.lower(input_text)
x = list('')
for i in lowercase_input:
x.append(i)
您可以使用collections.Counter直接進行操作。
考慮以下示例。
from collections import Counter
s = "example"
c = Counter(s)
# Counter({'e': 2, 'x': 1, 'a': 1, 'm': 1, 'p': 1, 'l': 1})
您還可以通過
c.most_common(1) #[('e', 2)]
還要注意,如果輸入是句子,則可能要避免空格,在這種情況下,您可以執行s = str.join("",s.split())
。
沒有任何導入,您可以使用常規詞典。
def checkio(text: str) -> str:
lowercase_input = text.lower()
x = {}
for i in lowercase_input:
x[i] = x.get(i, 0) + 1
return max(x.items(), key=lambda x: x[1])
key, value = checkio('asdafsasaaaa') # ('a', 7)
說明
dict.get
有一個可選的第二個參數,我們將其設置為0
。 這意味着如果字典中不存在該鍵,則x.get(i, 0)
將返回0
。 max
具有一個可選的key
參數,該參數接受匿名( lambda
)函數。 由於dict.items()
返回(key, value)
對的可迭代(key, value)
我們可以通過查看value
分量(第一個索引)來計算最大值。
性能
與@abc所示的 Counter
+ most_common
相比這效率低下。 具體來說, most_common
使用heapq
來減少時間復雜度。 另請參閱Python collections.Counter:most_common復雜度 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.