如何计算 python 列表中的单词列表

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

我有以下列表:

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

现在我必须开发一个名为 count_the_fruits 的函数,它将一个水果列表和一个名为单词的可变参数列表作为其参数。该函数应使用字典理解来创建单词(键)及其对应计数(值)的字典。

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

预期输出: {apple: 4, 'banana': 3, 'kiwi': 2}

如有任何帮助,我们将不胜感激。谢谢!

怎么样?

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)

它只给你一个计数的原因是因为你只搜索一个。试试这个:

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))

输出:

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

我找到你了,但是试着更好地问你的问题。

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()