繁体   English   中英

在python列表中对连续数字进行运算

[英]Operation on consecutive numbers in a python list

我正在尝试编写一个接受整数列表作为参数的函数。 然后,它将找到所有3个连续数字的运行,这些运行数字增加或减少1。它将返回每个运行的第一个元素的索引列表。 如果没有连续运行,则应返回None
示例: [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]返回[0, 4, 6, 7] 我将如何分解此问题的任何帮助将不胜感激。

我的尝试给了我错误的输出:

lst = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]


def cal_abs(a, b, c):

  return abs(a - b) == 1 and abs(b - c) == 1

def consecutive(lst):

   a = []

   for i in range(0,lst[-1]):

       if cal_abs(lst[i], lst[i+1], lst[i+2]):

           a.append(i)

          i += 1

   print(a)

现在,当我consecutive(lst)运行时consecutive(lst)

返回[0, 4, 5, 6] 错误。 有任何想法吗?

有几个问题。 我会给您一些提示,这些提示应该足以弄清楚并修复它们。

这个:

return abs(a - b) == 1 and abs(b - c) == 1

接受增加,然后减少,反之亦然。 这与您的问题陈述不太吻合,问题陈述似乎需要两次增加或两次减少。

另外,主循环lst[-1]的上限采用了最后一个元素的值 -为什么?

您将需要检查> b> c或<b <c。 你可以看到下面的代码

lst = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]

def cal_abs(a, b, c):
    if a < b and b < c and (a-b) == -1 and (b-c) == -1:
        return True
    elif a > b and b > c and (a-b) == 1 and (b-c) == 1:
        return True
    else:
        return False

def consecutive(lst):
    a = []
    for i in range(0,len(lst)-3):
        if cal_abs(lst[i], lst[i+1], lst[i+2]):
            a.append(i)
            i += 1
    print(a)

consecutive(lst)

我建议制作一个辅助函数isARun(f, m, l)

def isARun(f,m,l):
    return (f == m-1 and f == l-2) or (f == m + 1 and f == l+2)

然后,您要在主要函数中consecutive执行一个for循环,如下所示。

for i in range(len(l) - 3):
    if (isARun(l[i], l[i+1], l[i+2])):
        a.append(i)
if len(a) == 0:
    return None
return a

试试这个简单的解决方案:

my_list = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]

consective_indices = []
for index, num in enumerate(my_list[:-2]):
    immediate_next = abs(my_list[index + 1])
    next = abs(my_list[index + 2])
    if (num + 1 == immediate_next and num + 2 == next) or 
              (num - 1 == immediate_next and num - 2 == next):

        consective_indices.append(index)

print consective_indices

希望这可以帮助。 干杯!

暂无
暂无

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

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