计算列表中小于零的元素数量

定义一个函数计算列表中小于零的元素数量。大家看一下不同的思路,应该还是很有启发的。

不使用循环的方法

def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    nums.append(0)
    nums.sort()
    return nums.index(0)

使用循环的方法 1

def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0
    for num in nums:
        if num < 0:
            n_negative = n_negative + 1
    return n_negative

使用循环的方法 2

def count_negatives(nums):
    return len([num for num in nums if num < 0])

使用循环的方法 3

def count_negatives(nums):
    # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
    # Python where it calculates something like True + True + False + True to be equal to 3.
    return sum([num < 0 for num in nums])

这个算法很有趣,利用True==1的特性进行计算。

以上三个方法哪一个是最好的是一个很主观的判断。用更少的代码解决问题总是好的,但Python的哲学 The Zen of Python也不要忘了:

Readability counts. 需要考虑易读性。
Explicit is better than implicit. 一目了然的要比晦涩的更好。

内容参考了Kaggle上的内容(https://www.kaggle.com/colinmorris/loops-and-list-comprehensions)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Cheat_Sheet ---Keras Cheat_Sheet ---Matlab Cheat_Sheet --...
    jiandanjinxin阅读 9,694评论 0 107
  • Introduction This document gives coding conventions for t...
    wuutiing阅读 10,135评论 0 9
  • 鸭子类型 动态语言中经常提到鸭子类型,所谓鸭子类型就是:如果走起路来像鸭子,叫起来也像鸭子,那么它就是鸭子(If ...
    onepedalo阅读 3,541评论 0 2
  • 原文 原文下载之后的格式略有点不友好,利用简述的markdown,编辑一下.版权归原作者 PEP Index > ...
    大飞哥阅读 7,288评论 0 0
  • 冷树寂寥垂垂立,忧思落叶何处归。 偶闻鸟声忆仲夏,映尽山林是孤影。 满树相思寄春归,横风与我怎传情。 又见炊烟袅袅...
    大清晨的小太阳阅读 1,508评论 0 2