简体   繁体   English

如何从现有列表创建字典? 键值必须是该键的重复次数

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

相关问题 如何在 Python 中的字典列表中使用另一个键列表中的值在字典中创建一个新键? - How to create a new key in dictionary with value from another key list from a list of dictionary in Python? 如何使用python从列表中获取字典,将列表条目作为键,并将列表中的项数作为值? - How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python? Python:如何遍历词典列表并将每个词典作为值添加到具有唯一键的新词典中-无需重复 - Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats 如何从python中具有相同键和值的字符串列表创建字典 - How to create a dictionary from a list of strings with same key, value in python 从2个列表生成字典,如果值为None,则必须为'key:'None' - Generate dictionary from 2 list, if value is None it must be 'key : 'None'' 如何从未知数量的字典列表中返回键值字典对? - How can I return key value dictionary pairs from a list of dictionaries of unknown amount? 如何从字典中创建给定键的列表 - How to create a list of a given key from dictionary 如何从列表中的键获取字典值? - How to get dictionary value from key in a list? 如何将键和值从字典连接到列表? - How to concat key and value from dictionary to list? 如何将现有列表转换为 Python 中字典的键值对? - How to turn an existing list into a key-value pair for a dictionary in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM