社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Arif Shahriar • 5 年前 • 1540 次点击  

我有以下清单:

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

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

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

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

任何帮助都将不胜感激。谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54439
 
1540 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Exosylver
Reply   •   1 楼
Exosylver    5 年前

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()
Daniel
Reply   •   2 楼
Daniel    5 年前

怎么样?

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)
Sayandip Dutta
Reply   •   3 楼
Sayandip Dutta    5 年前

它只给你一个计数是因为你只在寻找一个。试试这个:

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}