0

I have a list of strings in my program, for example:

[ 'home', 'dog', 'park', 'house', 'hotel', 'fire' ]

and I want to know which is the most first frequent letter .

for example in that string is the letter H because it is in hotel, house and home.

I tried just 2 for cycles but I didn't get the result

Francesco
  • 13
  • 2
  • Just 2 what? You should loop over the array, use `element[0]` to get the first character, and count the frequencies of those. – Barmar Nov 11 '22 at 21:30

5 Answers5

3

You could create a list of the first letters and then use the max() function to get the highest number of occurrences in it.

lst = ['home', 'dog', 'park', 'house', 'hotel', 'fire']
max([item[0] for item in lst], key=lst.count)

output

'h'
yutytuty
  • 41
  • 3
1

You can get the first letter of each work with a list comprehension.

Then you can use collections.Counter to find the frequency of each letter and find the maximum of the returned dictionary:

import collections

words = [ 'home', 'dog', 'park', 'house', 'hotel', 'fire' ]

first_letters = [w[0] for w in words]

f = collections.Counter(first_letters)

print(max(f, key=f.get))

Output: h

DeusDev
  • 538
  • 6
  • 15
1

You could create a list of the first character of each string and then use python's statistics module like so:

from statistics import mode
def most_common_first_letter(words):
    first_letters = []
    for word in words:
        first_letters.append(word[0])
    return mode(first_letters)
    

This uses the mode function to find the most common letter in the list of first letters.

James_481
  • 156
  • 10
0

You can use Counter from collections module, for example:

from collections import Counter


list_ = ['home', 'dog', 'park', 'house', 'hotel', 'fire']


if __name__ == '__main__':
    counter = Counter(word[0] for word in list_)
    print(counter.most_common(1)[0][0])
0

Extracting first elemnt from list item & Using collections

from collections import Counter
ls= [ 'home', 'dog', 'park', 'house', 'hotel', 'fire' ]
ls = [w[0] for w in ls]

s=(Counter(ls))

print(max(s, key=s.get))

output #

h