我如何比较数组中x的值和x +1的值?

问题描述 投票:1回答:4

我注意到,在很多编码问题中,有必要将x与x + 1进行比较,尽管我从来没有找到一种好的方法。

我该怎么办?可能吗抱歉,如果这似乎是一个菜鸟问题,我还不是很好。

这是我通常尝试的:

       for x in range(len(nums)):
                    if nums[x] > nums[x+1 < len(nums)]:
                        count +=1 
python
4个回答
1
投票

没问题!我们都从某处开始:)这是一种实现方法:

for x in range(len(nums) - 1):
   if nums[x] > nums[x+1]:
       #do something


1
投票

len(nums)将返回数组中值的number,并且当您遍历数组时,将使用索引0而不是1来访问该数组中的第一个值。

例如:

nums = [1,3,5,7]
len(nums) == 4

如果您运行

for x in range(len(nums)):
   if nums[x] > nums[x+1]:
       #code here

您将在nums [x + 1]处遇到错误,因为在最后一次迭代中,它变为nums [3 + 1],即nums [4],并且该索引不在该数组中。您的最后一个索引是3。

所以您真正想要的是

for x in range(len(nums)-1):
   if nums[x] > nums[x+1]:
       #code here

0
投票

您可以使用reduce

例如,要获取列表的最大值,您可以执行以下操作

import functools 
arr = [1,2,3,4,5]
print(functools.reduce(lambda a,b : a if a > b else b, arr))

输出

5

answer也很好用。


0
投票

您可以使用此帮助器功能遍历任何序列的相邻对:

def pairwise(iterable):
    "s -> [[s0,s1], [s1,s2], [s2, s3], ...]"
    a, b = iter(iterable), iter(iterable)
    next(b, None)
    return zip(a, b)


nums = 1, 5, 3, 7
count = 0
for x, x1 in pairwise(nums):
    if x > x1:
        count += 1
© www.soinside.com 2019 - 2024. All rights reserved.