在Python中编写一个函数,它返回一个大于零的数组中的数字计数

时间:2011-10-31 00:49:18

标签: python

例如,假设我们调用函数countPositive([1,2,3]),它将返回3.或者如果我们有数组[-1,0,1],则有一个正数,所以函数将返回1.依此类推。

8 个答案:

答案 0 :(得分:8)

def countPositive(nums):
        return sum(1 for x in nums if x > 0)

答案 1 :(得分:6)

def countPositive(nums):
    return len(filter(lambda x: x > 0, nums))

一些timeit结果(在新的macbook air w / 1.8 i7,4 gigs和cpython 2.7上):

filter + len

$ python -m timeit "l = [-1, 0, 1] * 100; len(filter(lambda x: x > 0, l))"  
  10000 loops, best of 3: 49.9 usec per loop

$ python -m timeit "l = [-1, 0, 1] * 1000; len(filter(lambda x: x > 0, l))"                                                                  
1000 loops, best of 3: 476 usec per loop

$ python -m timeit "l = [-1, 0, 1] * 10000; len(filter(lambda x: x >  0, l))" 
100 loops, best of 3: 4.86 msec per loop

sum(由hochl推荐):

$ python -m timeit "l = [1, 2, 3] * 100; sum(1 for x in l if x > 0)" 
10000 loops, best of 3: 35.1 usec per loop

$ python -m timeit "l = [1, 2, 3] * 1000; sum(1 for x in l if x > 0)"
1000 loops, best of 3: 336 usec per loop

$ python -m timeit "l = [1, 2, 3] * 10000; sum(1 for x in l if x > 0)"
100 loops, best of 3: 3.4 msec per loop

因此sum版本稍快一点,但我认为len + filter更具可读性。

答案 2 :(得分:1)

    greaterThanZero = 0
    for i in array:
        if i > 0:
             greaterThanZero += 1

    return greaterThanZero

答案 3 :(得分:0)

你可以这样做:

def countPositive(array):
  count=0
  for i in array: 
    if i>0: 
      count = count +1
  return count

答案 4 :(得分:0)

奇怪的是,列表理解是最快的:

$ python -m timeit "l = [-1, 0, 1] * 10000; len([n for n in l if n > 0])"
1000 loops, best of 3: 1.1 msec per loop

使用sum :(较慢)

$ python -m timeit "l = [-1, 0, 1] * 10000; sum(1 for x in l if x > 0)"
1000 loops, best of 3: 1.3 msec per loop

使用过滤器:(最慢)

$ python -m timeit "l = [-1, 0, 1] * 10000; len(filter(lambda x: x >  0, l))" 
100 loops, best of 3: 2.89 msec per loop

答案 5 :(得分:0)

reduce(lambda x,y: x+int(y>0),[1, 2, 1, 4,5],0)

答案 6 :(得分:0)

这也有效:

function countMoreThanZero(a):

    for i in a:

        if i > 0:

            sum += 1

    return sum

答案 7 :(得分:0)

如果您不想使用lambda

from operator import lt
from functools import partial

def count_positive(nums):
    return len(filter(partial(lt, 0), nums))

应该更快,因为它避免了lambda。