[英]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.