简体   繁体   English

Python-如何返回一个字典,用于计算字符串列表中的出现次数?

[英]Python- How to return a dictionary that counts occurrences in a list of strings?

I'm trying to make a function that counts occurrences of the first letters of a list of strings and returns them as a dictionary. 我正在尝试创建一个函数来计算字符串列表的第一个字母的出现次数并将它们作为字典返回。

For example: 例如:

list=["banana","ball", "cat", "hat"] list = [“banana”,“ball”,“cat”,“hat”]

dictionary would look like: {b:2, c:1, h:1} 字典看起来像:{b:2,c:1,h:1}

Here is the code I have which iterates but doesn't count properly. 这是我所拥有的代码,它迭代但不正确。 That's where I'm getting stuck. 那就是我陷入困境的地方。 How do I update the values to be count? 如何更新要计数的值?

def count_starts(text):
    new_list=[]
    for word in range(len(text)):
        for letter in text[word]:
            if letter[0]=='':
                new_list.append(None)
            else:
                new_list.append(letter[0])

    new_dict= {x:new_list.count(x) for x in new_list}


    return new_dict

Also, how can I avoid the out of range error given the following format: 另外,如果给出以下格式,如何避免超出范围错误:

def count_starts(text):
    import collections
    c=collections.Counter(x[0] for x in text)
    return c

Also, what do I need to do if the list contains "None" as a value? 另外,如果列表中包含“None”作为值,我还需要做什么? I need to count None. 我需要算无。

Problem with your code is that you seem to iterate on all letters of the word. 您的代码问题在于您似乎迭代了单词的所有字母。 letter[0] is a substring of the letter (which is a string). letter[0]letter[0]的子字符串(字符串)。

You'd have to do it more simply, no need for a double loop, take each first letter of your words: 你必须更简单地完成它,不需要双循环,取你单词的每个首字母:

for word in text:
    if word:  # to filter out empty strings
        first_letter = word[0]

But once again collections.Counter taking a generator comprehension to extract first letter is the best choice and one-liner (with an added condition to filter out empty strings): 但是再次collections.Counter .Counter采用生成器理解来提取第一个字母是最好的选择和单行(添加条件来过滤掉空字符串):

import collections
c = collections.Counter(x[0] for x in ["banana","ball", "cat", "", "hat"] if x)

c is now a dict: Counter({'b': 2, 'h': 1, 'c': 1}) c现在是一个dict: Counter({'b': 2, 'h': 1, 'c': 1})

one variant to insert None instead of filtering out empty values would be: 插入None而不是过滤掉空值的一个变量是:

c = collections.Counter(x[0] if x else None for x in ["banana","ball", "cat", "", "hat"])
my_list=["banana","ball", "cat", "hat"] 

my_dict = dict()

for word in my_list:
   try:
      my_dict[word[0]] += 1
   except KeyError:
      my_dict[word[0]] = 1

This increases the value of the key by 1 for the already existing key, and if they key has not been found before it creates it with the value 1 这会将现有密钥的密钥值增加1,如果在创建密钥之前未找到它们,则使用值1

Alternative: 替代方案:

my_list=["banana","ball", "bubbles", "cat", "hat"] 
my_dict = dict()

for word in my_list:
    if word[0] in my_dict.keys():
        my_dict[word[0]] += 1
    else:
        my_dict[word[0]] = 1

Also, what do I need to do if the list contains "None" as a value? 另外,如果列表中包含“None”作为值,我还需要做什么? I need to count None. 我需要算无。

removing None 删除无

lst_no_Nones = [x for x in lis if x != None]

count None 数无

total_None = (sum(x != None for x in lst))

you need counter: 你需要柜台:

 from collections import Counter
 lst = ["banana","ball", "cat", "hat"]
 dct = Counter(lst)

Now, dct stores the number of times every element in lst occurs. 现在,dct存储lst中每个元素出现的次数。

dct = {'b': 2, 'h': 1, 'c': 1} dct = {'b':2,'h':1,'c':1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM