繁体   English   中英

如何计算列表中的数字大于其后的数字的次数?

[英]How to count the number of times a number in a list is greater than the number after it?

我想在列表中查看该数字大于其后的数字的次数。

example = [2, 3, 4, 5, 7, 8, 6, 2, 3, 4, 5]

def lstCount(lst):
    counter = 0
    if lst[0] < lst[1]:
        counter + 1 
        lstCount(lst[1:])
    else:
        lstCount(lst[1:])

    return counter

lstCount(example)

这应该产生2,但是我的列表索引超出范围。

it = iterator(lst)
next(it, None)
count = sum(a > b for a, b in zip(lst, it))

或者简单地

count = sum(a > b for a, b in zip(lst, lst[1:]))

您需要添加一个基本情况,其中lst仅为1个元素。 否则,当它检查lst[1] ,它将尝试检查不存在的元素,并且您可能会遇到超出范围的错误。 此外, counter + 1不执行任何操作。 我建议只返回值,而不要使用计数器。

def lstCount(lst):
    if len(lst) == 1:
        return 0
    elif lst[0] > lst[1]:
        return 1 + lstCount(lst[1:])
    return lstCount(lst[1:])

另一个直接的解决方案:遍历前n-1个元素并比较列表中的当前元素和下一个元素。

example = [2, 3, 4, 5, 7, 8, 6, 2, 3, 4, 5]
count = 0
for i in range(len(example) - 1):#get size of example then decrease by 1
    if example[i] < example[i + 1]:#visit element by index
        count = count + 1
print count

Output:
8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM