简体   繁体   中英

Counting the letters of a string in a list and outputting the amount each letter appears in each string

For example I have a list containing these strings:

list1 = ["apple", "avocado", "pear", "orange"]

And I want the output to look like this:

apple contains 1 a
avocado contains 2 a
pear contains 1 a
orange contains 1 a
avocado contains 1 c
...

And so on for each letter appearing in the word. Thanks in advance

You could use the count function to print characters in a string The following example shows the working of count() function on a string.

str_count1 = list1[0].count('a') 
print("The count of 'a' is", str_count1)

(check this for further explanation https://www.guru99.com/python-string-count.html

First of all, collections.Counter should be the more efficient way to go for large datasets. For a small dataset like given, I wouldn't mind using double for-loop to perform str.count() , which easily preserves the ordering of words and alphabets to be printed.

Code

list1 = ["apple", "avocado", "pear", "orange"]
chars = sorted(set(''.join(list1)))  # get the appearing characters sorted

for ch in chars:
    for word in list1:
        n = word.count(ch)
        if n > 0:
            print(f"{word} contains {n} {ch}")

Output

apple contains 1 a
avocado contains 2 a
pear contains 1 a
orange contains 1 a
avocado contains 1 c
avocado contains 1 d
apple contains 1 e
pear contains 1 e
...
orange contains 1 r
avocado contains 1 v

a few ways are there to do this, one of them is using counter function from collection.

from collections import Counter
test_str = "GeeksforGeeks"
res = Counter(test_str)
print ("Count of all characters in GeeksforGeeks is :\n "
                                       +  str(res))

output:

Count of all characters in GeeksforGeeks is : 
Counter({'e': 4, 's': 2, 'k': 2, 'G': 2, 'o': 1, 'r': 1, 'f': 1})

source: geeksforgeeks

just google "finding frequency of each character in string".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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