[英]Python- How to return a dictionary that counts occurrences in a list of strings?
我正在尝试创建一个函数来计算字符串列表的第一个字母的出现次数并将它们作为字典返回。
例如:
list = [“banana”,“ball”,“cat”,“hat”]
字典看起来像:{b:2,c:1,h:1}
这是我所拥有的代码,它迭代但不正确。 那就是我陷入困境的地方。 如何更新要计数的值?
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
另外,如果给出以下格式,如何避免超出范围错误:
def count_starts(text):
import collections
c=collections.Counter(x[0] for x in text)
return c
另外,如果列表中包含“None”作为值,我还需要做什么? 我需要算无。
您的代码问题在于您似乎迭代了单词的所有字母。 letter[0]
是letter[0]
的子字符串(字符串)。
你必须更简单地完成它,不需要双循环,取你单词的每个首字母:
for word in text:
if word: # to filter out empty strings
first_letter = word[0]
但是再次collections.Counter
.Counter采用生成器理解来提取第一个字母是最好的选择和单行(添加条件来过滤掉空字符串):
import collections
c = collections.Counter(x[0] for x in ["banana","ball", "cat", "", "hat"] if x)
c
现在是一个dict: Counter({'b': 2, 'h': 1, 'c': 1})
插入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
这会将现有密钥的密钥值增加1,如果在创建密钥之前未找到它们,则使用值1
替代方案:
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
另外,如果列表中包含“None”作为值,我还需要做什么? 我需要算无。
删除无
lst_no_Nones = [x for x in lis if x != None]
数无
total_None = (sum(x != None for x in lst))
你需要柜台:
from collections import Counter
lst = ["banana","ball", "cat", "hat"]
dct = Counter(lst)
现在,dct存储lst中每个元素出现的次数。
dct = {'b':2,'h':1,'c':1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.