[英]How to create a dictionary from existing list? Key Value must be the amount of repeats for that key
I'm trying to create a "most wanted letter" program which takes a string as input and output should be the most repeated letter in that string. 我正在尝试创建一个“最想要的字母”程序,该程序将字符串作为输入,输出应该是该字符串中最重复的字母。 Currently, I can't figure out how to create a dictionary (eg dict.items():[("a", 2), ("b", 5)...]
). 目前,我不知道如何创建字典(例如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)
You may use collections.Counter to do it directly. 您可以使用collections.Counter直接进行操作。
Consider the following example. 考虑以下示例。
from collections import Counter
s = "example"
c = Counter(s)
# Counter({'e': 2, 'x': 1, 'a': 1, 'm': 1, 'p': 1, 'l': 1})
You can also get the most common letter with 您还可以通过
c.most_common(1) #[('e', 2)]
Note also that in case the input is a sentence you may want to avoid whitespace and in this case you can do something like s = str.join("",s.split())
. 还要注意,如果输入是句子,则可能要避免空格,在这种情况下,您可以执行s = str.join("",s.split())
。
Without any imports, you can use a regular dictionary. 没有任何导入,您可以使用常规词典。
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)
Explanation 说明
dict.get
has an optional second parameter, which we set to 0
. dict.get
有一个可选的第二个参数,我们将其设置为0
。 This means if the key does not exist in the dictionary x.get(i, 0)
will return 0
. 这意味着如果字典中不存在该键,则x.get(i, 0)
将返回0
。 max
has an optional key
parameter which accepts an anonymous ( lambda
) function. max
具有一个可选的key
参数,该参数接受匿名( lambda
)函数。 Since dict.items()
returns an iterable of (key, value)
pairs, we can calculate the maximum by looking at the value
component (1st index). 由于dict.items()
返回(key, value)
对的可迭代(key, value)
我们可以通过查看value
分量(第一个索引)来计算最大值。
Performance 性能
This is inefficient versus Counter
+ most_common
as shown by @abc . 与@abc所示的 Counter
+ most_common
相比这效率低下。 Specifically, most_common
uses heapq
to reduce time complexity. 具体来说, most_common
使用heapq
来减少时间复杂度。 See also Python collections.Counter: most_common complexity . 另请参阅Python collections.Counter:most_common复杂度 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.