美文网首页
计算列表中小于零的元素数量

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

作者: Michael_lllll | 来源:发表于2018-10-22 06:52 被阅读0次

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

不使用循环的方法

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)

相关文章

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

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

  • Swift_集合 arr.removeFirst(_ k: In

    【从头部/末尾删除给定数量的元素】 “k”必须大于或等于零,并且必须小于或等于集合中元素的数量。

  • 贪心算法

    376.摆动序列(mediun)计算出相邻元素之间的差值,若相邻非零差值的乘积小于零那么证明当前元素加入序列中能够...

  • python列表(List)常见数据处理方式

    列表添加元素 append方法 获取列表长度 len() 统计列表中不同元素的各自的数量

  • LeetCode-315-计算右侧小于当前元素的个数

    LeetCode-315-计算右侧小于当前元素的个数 315. 计算右侧小于当前元素的个数[https://lee...

  • 计数排序

    归属:时空权衡思想中的输入增强技术 简介:该算法比较简单。针对待排序列表中的每一个元素,算出列表中小于该元素的元素...

  • 进行单元测试

    assert len(lists) >=5,'列表元素个数小于5'

  • python笔记 基本数据类型二

    列表 list : 对象值以中括号内表示,元素以逗号分隔。 li = [“元素零“,[”列表套列表“,[”里面还可...

  • 数据结构 --列表

    列表 1.列表的特性介绍 用[]括起来,里面可以有n个或零个元素 列表的元素是可变的列表的元素可以是python中...

  • Redis 数据结构之链表

    当一个列表键包含了数量比较多的元素,又或者列表中包含的元素都是比较长的字符串时,Redis 就会使用链表作为列表键...

网友评论

      本文标题:计算列表中小于零的元素数量

      本文链接:https://www.haomeiwen.com/subject/pflwzftx.html