Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算列表中某个数字大于其后数字的次数?_Python - Fatal编程技术网

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

Python 如何计算列表中某个数字大于其后数字的次数?,python,Python,我想在列表中看到一个数字大于它后面的数字的次数 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(exampl

我想在列表中看到一个数字大于它后面的数字的次数

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)
example=[2,3,4,5,7,8,6,2,3,4,5]
def lst计数(lst):
计数器=0
如果lst[0]

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

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

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

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

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

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

count = sum(a > b for a, b in zip(lst, 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
example=[2,3,4,5,7,8,6,2,3,4,5]
计数=0
对于范围内的i(len(示例)-1):#获取示例的大小,然后减少1
如果示例[i]<示例[i+1]:#按索引访问元素
计数=计数+1
打印计数
输出:
8.
另一种直接解决方案: 遍历前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
example=[2,3,4,5,7,8,6,2,3,4,5]
计数=0
对于范围内的i(len(示例)-1):#获取示例的大小,然后减少1
如果示例[i]<示例[i+1]:#按索引访问元素
计数=计数+1
打印计数
输出:
8.

在最后一个元素上调用lstCount(lst[1:])时,代码中会发生什么?另外,计数器是在本地声明的。当您对最后一个元素调用lstCount(lst[1:])时,代码中会发生什么?此外,计数器是本地声明的。请添加一些文本来解释您的代码,以提高您的答案的质量。我认为这足够简单,只需通过索引遍历前n-1个元素,并比较当前和下一个元素。很好,请将其添加到您的答案中,因为您应该假设OP不知道这一点。在你看来,首先想想OP为什么问这个问题。请添加一些文本来解释你的代码,以提高你的答案的质量。我认为这很简单,只需按索引遍历前n-1个元素并比较当前和下一个元素。很好,请将此添加到您的答案中,因为您应该假设OP不知道这一点。在你看来,想一想为什么OP会问这个问题。