【问题标题】:Python find succesive numbers in array/listPython在数组/列表中查找连续的数字
【发布时间】:2017-03-29 08:25:38
【问题描述】:

我有一个像 arr = [1,2,3,10,11,15] 这样的数组,我想从中获取每个连续数字块的左右数字,即 [0,4,9,12,14,16]。

【问题讨论】:

  • 你有什么尝试吗?
  • 是的,但不值得一提,因为它根本不起作用。
  • 从期望的结果看来,数字不必是连续的。 15 的处理方式相同。您绝对可以编写一个非常冗长和明确的for 循环。它不会很优雅,但你可以做到。

标签: python arrays


【解决方案1】:
from itertools import groupby
from operator import itemgetter
arr = [1,2,3,10,11,15]
new_list = []
for m, n in groupby(enumerate(arr), lambda (i, x): i-x):
    t = map(itemgetter(1), n) 
    new_list.append(t[0]-1)
    new_list.append(t[-1]+1)

new_list
Out[]: [0, 4, 9, 12, 14, 16]

【讨论】:

    【解决方案2】:

    所以你想在一个循环中遍历数组,检查 index[i] 处的数字是否大于 index[i+1] 处的数字并将其存储在数组中/将其打印到控制台/ect .如果该检查为真(或为假,取决于您要如何执行此操作。)

    【讨论】:

    • 这应该是一个答案吗?
    • 根据“问题”...是的
    【解决方案3】:

    这样做的方式很糟糕:

    def getMissing( lst ):
        a = sorted(lst) # in case its not already sorted
        a.append( a[-1] + 10000) #insert one dummy bigger to ease iteration
        missing = []
    
        for i in xrange(len(a)-1):
            if a[i] - a[i-1] != 1:
                missing.append( a[i] -1)
            if a[i+1] - a[i] != 1:
                missing.append( a[i] +1)
        return missing    
    
    print getMissing([1,2,3,10,11,15])
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 2017-05-23
      • 2011-12-18
      • 2020-01-16
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      相关资源
      最近更新 更多