返回字典中的项目数

发布于 2025-01-19 21:39:21 字数 688 浏览 1 评论 0原文

我想修改此函数以返回字典中以每个字母开头的项目数。例如:

list= ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(list))
{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}

到目前为止,我可以返回第一个字母和单词,但不能返回不同的字母数。

def letterCounter(wrdLst):
    output = {}
    for word in wrdLst:
        letter = word[0]
        if letter in output:
            output[letter].append(word)
        else:
            output[letter] = [word]
    return output

list = ["apple", "pear", "brown", "red"]
print(letterCounter(list))

这将返回字母而不是数字:输出:

{'I': ['I'], 's': ['say'], 'w': ['what'], 'm': ['mean'], 'a': ['and']}

I want to modify this function to return the number of items in the dictionary that begin with each letter. For example:

list= ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(list))
{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}

So far I can return the first letter and words, but not the number of letters that are different.

def letterCounter(wrdLst):
    output = {}
    for word in wrdLst:
        letter = word[0]
        if letter in output:
            output[letter].append(word)
        else:
            output[letter] = [word]
    return output

list = ["apple", "pear", "brown", "red"]
print(letterCounter(list))

this would return the letters instead of number: output:

{'I': ['I'], 's': ['say'], 'w': ['what'], 'm': ['mean'], 'a': ['and']}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

鹤仙姿 2025-01-26 21:39:21

不要附加该单词​​,而是增加一个计数器。

def letterCounter(wrdLst):
    output = {}
    for word in wrdLst:
        letter = word[0]
        if letter in output:
            output[letter] += 1
        else:
            output[letter] = 1
    return output

您还可以使用标准collections 模块。

from collections import Counter

def letterCounter(wrdLst):
    return Counter(word[0] for word in wrdLst)

Don't append the word, increment a counter.

def letterCounter(wrdLst):
    output = {}
    for word in wrdLst:
        letter = word[0]
        if letter in output:
            output[letter] += 1
        else:
            output[letter] = 1
    return output

You can also use the standard collections module.

from collections import Counter

def letterCounter(wrdLst):
    return Counter(word[0] for word in wrdLst)
孤星 2025-01-26 21:39:21

如果你很喜欢使用 numpy,你可以使用它独特的功能来完成你想要做的事情。在 np.unique 调用内部,我进行了列表理解,以提取每个单词的第一个字母并确保它是小写的。然后,unique 函数返回唯一的起始字母,并在启用 return_counts 的情况下给出它们出现的次数。

import numpy as np

words = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
unique, counts = np.unique([word[0].lower() for word in words], return_counts=True)

for (val, count) in zip(unique, counts):
    print (val, count)

If you are cool using numpy, you can just use its unique function to do what you are trying to do. Below inside of the np.unique call, I do a list comprehension to pull the first letter off of each word and make sure it is lowercase. Then the unique function returns the unique starting letters and with return_counts enabled gives their number of occurrences.

import numpy as np

words = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
unique, counts = np.unique([word[0].lower() for word in words], return_counts=True)

for (val, count) in zip(unique, counts):
    print (val, count)
长发绾君心 2025-01-26 21:39:21

另一个计数器方式:

from collections import Counter

def letterCount(words):
    return Counter(next(zip(*words)))

words = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(words))

Another Counter way:

from collections import Counter

def letterCount(words):
    return Counter(next(zip(*words)))

words = ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(words))
月亮坠入山谷 2025-01-26 21:39:21

使用违约将使代码更简洁如下:

from collections import defaultdict

def letterCounter(wrdLst):
    d = defaultdict(int)
    for w in wrdLst:
        d[w[0]] += 1
    return dict(d) # return a regular dictionary
    
print(letterCounter(['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']))

输出:

{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}

Using a defaultdict will make the code more concise as follows:

from collections import defaultdict

def letterCounter(wrdLst):
    d = defaultdict(int)
    for w in wrdLst:
        d[w[0]] += 1
    return dict(d) # return a regular dictionary
    
print(letterCounter(['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']))

Output:

{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}
深海里的那抹蓝 2025-01-26 21:39:21

您还可以将首字母写给字符串,然后使用str.Count()制作dict:

def letter_count(wrdLst):
   s = ''
   for i in wrdLst:
      s += i[0]
   d = {}
   for i in s:
       d[i] = s.count(i)
   return d

You can also make the initial letters to a string and then use str.count() to make the dict:

def letter_count(wrdLst):
   s = ''
   for i in wrdLst:
      s += i[0]
   d = {}
   for i in s:
       d[i] = s.count(i)
   return d
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文