Python- How to return a dictionary that counts occurrences in a list of strings? -
i'm trying make function counts occurrences of first letters of list of strings , returns them dictionary.
for example:
list=["banana","ball", "cat", "hat"]
dictionary like: {b:2, c:1, h:1}
here code have iterates doesn't count properly. that's i'm getting stuck. how update values count?
def count_starts(text): new_list=[] word in range(len(text)): letter in text[word]: if letter[0]=='': new_list.append(none) else: new_list.append(letter[0]) new_dict= {x:new_list.count(x) x in new_list} return new_dict
also, how can avoid out of range error given following format:
def count_starts(text): import collections c=collections.counter(x[0] x in text) return c
also, need if list contains "none" value? need count none.
problem code seem iterate on letters of word. letter[0]
substring of letter (which string).
you'd have more simply, no need double loop, take each first letter of words:
for word in text: if word: # filter out empty strings first_letter = word[0]
but once again collections.counter
taking generator comprehension extract first letter best choice , one-liner (with added condition filter out empty strings):
import collections c = collections.counter(x[0] x in ["banana","ball", "cat", "", "hat"] if x)
c
dict: counter({'b': 2, 'h': 1, 'c': 1})
one variant insert none
instead of filtering out empty values be:
c = collections.counter(x[0] if x else none x in ["banana","ball", "cat", "", "hat"])
Comments
Post a Comment