繁体   English   中英

如何从列表中的索引 1 开始并在列表中的最后一个元素之前结束

[英]How do I start at index 1 in my list and end just before the last element in the list

enter code here   count = 0
                  for i in range(1,len(listOfmountains)-1):
                      if listOfmountains[i+1] > listOfmountains[i]:
                      count +=1
                   elif listOfmountains[i-1] > listOfmountains[i]:
                         count +=1
                   return count
enter code hereif __name__ == "__main__":

testcase = [1000,1250,1200,1300,1100,1500,1400]
print("{} is the number of peaks in {}".format(countPeaks(testcase),testcase))

testcase = [1000,1250,2000,1600,2100]
print("{} is the number of peaks in {}".format(countPeaks(testcase),testcase))
testcase =  [2000, 1250, 3500, 1600, 1400, 1650, 1800, 850, 1775, 1900]
print("{} is the number of peaks in {}".format(countPeaks(testcase), testcase))

我想从 1 开始并以最后一个数字之前的数字结束。 我正在遍历一个列表。 顺便说一下,我想看看峰值的数量,不包括第一个数字和最后一个数字。

range(1, len(listOfMountains)) ,您只需要将range(1, len(listOfMountains))更改为range(1, len(listOfMountains)-1

range()的方法签名如下:

range(start, stop, step)

range()将创建一个包含起始值并排除终止值的范围。 例如:

print([i for i in range(0,4)])

只会打印值: [0,1,2,3] (注意它不包括停止值)。

只需从 range 函数的上界减去 1:

count = 0
for i in range(1,len(listOfmountains)-1):
    if listOfmountains[i+1] > listOfmountains[i]:
         count +=1
    elif listOfmountains[i-1] > listOfmountains[i]:
         count +=1
return count

暂无
暂无

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

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