简体   繁体   中英

Create a function that counts words/strings in a list of a specific length - Python 3

Trying to create a word counting function that will count how many words of a given length are in a list.

my_list =['full', 'hello', 'light', 'too', 'wise']

If I wanted to search that list for 4 letter words...I was thinking:

def word_count(list, length):
    count = 0
    if len(list) == 3: #I know this is wrong 
                       #it's just an example of what I was thinking
    count += 1
    return count

Any help is appreciated!

Try that, it's more Pythonic:

def word_count(word_list, word_length):
    return len(filter(lambda x: len(x) == word_length, word_list))

Is this what you want?

def countWordlen(lst):
    count = 0
    for i in lst: # loop over the items of the list
        if len(i) == 3: # if the len the items (words) equals 3 increment count by 1
            count = count + 1
    return count
lst =['full', 'hello', 'light', 'too', 'wise']
countWordlen(lst)

OUT: 1

@Mbruh you were almost there,you just need to loop through the whole list like

 my_list =['full', 'hello', 'light', 'too', 'wise']
 def word_count(list, length):
     count=0
     for word in list:
         if len(word)==length:
            count=count+1
     return count
word_count(my_list,4)
2

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