【问题标题】:Counting the number of recurrences of an item of a list计算列表项的重复次数
【发布时间】:2017-11-27 21:29:23
【问题描述】:
l = "Hello world is me"
words_ = l.split()
print(l.split())

for item in words_ :
    if len(item) < 5 :
        print('Words with length less than 6:', item )
    elif len(item) == 5 :
        print('Words with length 5:', item )

这是我的代码,但是我希望它以指定的长度打印单词的数量,而是打印单词本身。有什么建议吗?

【问题讨论】:

  • sum(1 for w in l.split() if len(w)==5) 应该这样做。

标签: python list count


【解决方案1】:

您可以使用以下方法计算满足条件的元素数量:

sum(<i>condition</i> for <i>item</i> in <i>iterable</i>)

注意这里的<i>condition</i>必须是一个布尔值(因为True1,而False0,因此它总结了Trues,从而计算条件的次数满足)。

所以如果要统计长度小于5的元素个数,可以这样写:

number_of_words = sum(<b>len(word) &lt; 5</b> for <b>word</b> in <b>words_</b>)

或者对于长度为 5 的单词的数量:

number_of_words = sum(<b>len(word) == 5</b> for <b>word</b> in <b>words_</b>)

等等

【讨论】:

    【解决方案2】:

    您可以计算循环中的单词,但是使用根据单词大小过滤的生成器理解来提供 sum 更符合 Pythonic:

    >>> l = "Hello world is me"
    >>> sum(1 for w in l.split() if len(w)==5)
    2
    

    另一种变体是将测试结果转换为布尔值(这里的测试结果已经是布尔值,所以不需要bool()它),然后总结:

    sum(len(w)==5 for w in l.split())
    

    它非常适合测试一个条件,但是如果您想一次性计算匹配多个条件(len &lt; 5len == 5)的单词,经典循环仍然是最佳选择,因为它只在列表上迭代一次,并且您'很自然地使用 if/elsif 进行短路评估,这对 listcomps 来说太糟糕了,但这就是生活:

    less_than_5=exactly_5=0
    for item in l.split() :
        if len(item) < 5 :
            less_than_5 += 1
        elif len(item) == 5 :
            exactly_5 += 1
    

    【讨论】:

    • @MosesKoledoye:这里确实没有理由,一个潜在的问题可能是人们将其推广到布尔值的真实性,在这种情况下它可能会出错。跨度>
    • @WillemVanOnsem 我不明白它怎么会出错。或者我不明白你的意思:)
    • 例如尝试sum(x for x in l.split())。即使x 是假的,它也失败了。我想这就是威廉的意思。
    • @MosesKoledoye:如果我们不使用bool(..),人们会认为sum(..) 可以用作计数器。这样sum(len(x) for x in a) 计算a 中的元素数量,其中len(x) 具有真实性True。当然不是这样。我并不是说这个答案暗示了这一点,但它可能有点令人困惑。但是+1,所以没问题:)。
    【解决方案3】:

    除了现有的答案,您还可以使用filterlambda 函数来获取计数:

    # Python 2.x
    l = "Hello world is me"
    words_ = l.split()
    print "There are", len(filter(lambda x: len(x) < 5, words_)), "words less than 5 long"
    print "There are", len(filter(lambda x: len(x) == 5, words_)), "words exactly 5 long"
    
    # Python 3.x
    l = "Hello world is me"
    words_ = l.split()
    print ("There are", len(list(filter(lambda x: len(x) < 5, words_))), "words less than 5 long")
    print ("There are", len(list(filter(lambda x: len(x) == 5, words_))), "words exactly 5 long")
    

    【讨论】:

    • 请注意,这仅适用于 Python-2.x,因为在 Python-3.x 中 filter 返回一个可迭代对象,而不是一个列表。
    • @WillemVanOnsem 和不带括号的打印语句甚至会阻止你之前 :)
    • 编辑为包含 Python 3 版本
    【解决方案4】:

    我会先建立一个Counter,然后很容易提取你想要的信息。

    >>> from collections import Counter
    >>> s = "Hello world is me"
    >>> c = Counter(len(x) for x in s.split())
    >>> c
    Counter({2: 2, 5: 2})
    

    或者,您可以使用

    构建Counter
    c = Counter(map(len, s.split()))
    

    Counter 告诉你,你的句子有两个长度为 2 的单词和两个长度为 5 的单词。

    获取长度小于五个的单词数:

    >>> sum(num_words for length, num_words in c.items() if length < 5)
    2
    

    由于Counter 在查找缺失键时默认返回0,因此您可以通过发出相同的结果

    >>> sum(c[length] for length in range(1, 5))
    2
    

    这可能比第一个选项更容易阅读。

    获取长度为5的单词数非常简单:

    >>> c[5]
    2
    

    【讨论】:

      【解决方案5】:

      你必须找到每个单词的长度,然后你可以根据单词的长度来计算它们。

      使用range()max()sum() builtin functions 将大大简化代码:

      l = "Hello world is me"
      words = l.split()
      print(l.split())
      
      # create a dict to count words with the same length
      lengths = dict.fromkeys(
          range(1, max(len(word) for word in words) + 1),  # range's stop is exclusive
          0,  # default value
      )
      
      # count words' length
      for word in words:
          lengths[len(word)] += 1
      
      # count all words with length < 6
      print(
          'Words with length less than 6:',
          sum(value for key, value in lengths.items() if key < 6)
      )
      
      # count all words with length == 5
      print(
          'Words with length 5:',
          lengths.get(5, 0)  # faster than sum()
      )
      

      将打印:

      ['Hello', 'world', 'is', 'me']
      Words with length less than 6: 4
      Words with length 5: 2
      

      【讨论】:

        猜你喜欢
        • 2013-12-27
        • 2017-10-06
        • 2019-02-04
        • 2021-07-16
        • 1970-01-01
        • 2021-02-05
        • 2022-01-07
        • 2017-05-10
        • 1970-01-01
        相关资源
        最近更新 更多