【问题标题】:How to count a list of words from a list in python如何从python中的列表中计算单词列表
【发布时间】:2020-05-25 09:24:10
【问题描述】:

我有以下列表:

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(fruitList, word): lower_list = [i.lower() for i in fruitList] split_list = [i.split() for i in lower_list] count = [i.count(word) for i in split_list] print (sum(count)) count_the_fruits(fruits, "apple") 我已经这样做了,但这只是为了搜索一个项目,而不是项目列表。
  • 请把你的尝试放在问题本身,这里的人不会在不付出任何努力的情况下对问题感兴趣。这可能会帮助您获得反对票。
  • 感谢 Sayandip 的帮助和建议。我真的是新来的,但我会记住这一点。

标签: python dictionary-comprehension


【解决方案1】:

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

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}

【讨论】:

    【解决方案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()
    

    【讨论】:

      【解决方案3】:

      怎么样?

      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)
      

      【讨论】:

      • 谢谢,丹尼尔。它帮助我理解了上下文。只是想知道为什么我对我的问题投了反对票?有什么办法可以让我的问题更清楚吗?
      • 没问题 - 您可能被否决了,因为您没有在问题中包含代码(即使您在评论中包含)。不要太担心,如果您需要更多帮助,请务必告诉我们。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      相关资源
      最近更新 更多