简体   繁体   中英

How to count a list of words from a list in python

I have the following list:

fruits = [“apple”, “banana”, “grape”, “kiwi”, “banana”, “apple”, “apple”, “watermelon”, “kiwi”, “banana”, “apple”,]

Now I have to develop a function called count_the_fruits that would take as its arguments a list of fruits and a variable argument list called words. The function should use dictionary comprehension to create a dictionary of words (key) and their corresponding counts (value).

words = ["apple", "banana", "kiwi"]

Expect Output: {apple: 4, 'banana': 3, 'kiwi': 2}

Any help would be appreciated. Thanks!

I got you man, but try to ask your questions better.

words =[]


def count_the_fruits():
    for fruit in fruits:
        if words.count(fruit) >=1:
            continue
        words.append((fruit, fruits.count(fruit)))
    print(words)


fruits = ["apple", "banana","grape", "kiwi", "banana", "apple", "apple", "watermelon", "kiwi", "banana", "apple"]
count_the_fruits()

How about?

def count_the_fruits(fruits, fruits_to_check_for):

    # initialize variables:
    fruit_count = {}

    # iterate over each fruit in fruit list:
    for fruit in fruits_to_check_for:

        # count number of occurences:
        number_of_fruits = len([x for x in fruits if x==fruit])

        # add to dictionary:
        fruit_count[fruit] = number_of_fruits

    return fruit_count



if __name__ == '__main__':

    fruits = ['apple', 'banana', 'grape',       'kiwi', 
              'banana',  'apple', 'apple', 'watermelon', 
                'kiwi', 'banana', 'apple',]

    fruits_to_check_for = ['apple', 'banana']

    result = count_the_fruits(fruits, fruits_to_check_for)

    print(result)

The reason it is giving you only one count is because you are only searching for one. Try this:

fruits = ['apple', 'banana', 'grape', 'kiwi', 'banana', 'apple',
          'apple', 'watermelon', 'kiwi', 'banana', 'apple']
words = ["apple", "banana", "kiwi"]

def count_the_fruits(fruits, words):
    # This is a dict comprehension
    counts = {word: fruits.count(word) for word in words}
    return counts

print(count_the_fruits(fruits, words))

Output:

{'apple': 4, 'banana': 3, 'kiwi': 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