Python在数组/列表

时间:2017-03-29 08:25:38

标签: python arrays

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

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

所以你想要在循环中检查数组,检查索引[i]的数字是否大于索引[i + 1]的数字,并将其存储在数组/打印到控制台/等。如果该检查为真(或错误,取决于您希望如何做。)

答案 2 :(得分:0)

这是一种不恰当的方式:

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])
相关问题