识别列表中的连续数字组

时间:2010-01-28 11:57:15

标签: python list range continuous

我想在列表中识别连续数字组,以便:

myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])

返回:

[(2,5), (12,17), 20]

并且想知道最好的方法是什么(特别是如果Python内置了一些东西)。

编辑:注意我原本忘记提及个别号码应该作为单独的号码返回,而不是范围。

16 个答案:

答案 0 :(得分:106)

编辑2:回答OP新要求

ranges = []
for key, group in groupby(enumerate(data), lambda (index, item): index - item):
    group = map(itemgetter(1), group)
    if len(group) > 1:
        ranges.append(xrange(group[0], group[-1]))
    else:
        ranges.append(group[0])

输出:

[xrange(2, 5), xrange(12, 17), 20]

您可以使用范围或任何其他自定义类替换xrange。


Python文档对此非常简洁recipe

from operator import itemgetter
from itertools import groupby
data = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17]
for k, g in groupby(enumerate(data), lambda (i,x):i-x):
    print map(itemgetter(1), g)

输出:

[2, 3, 4, 5]
[12, 13, 14, 15, 16, 17]

如果您想获得完全相同的输出,可以这样做:

ranges = []
for k, g in groupby(enumerate(data), lambda (i,x):i-x):
    group = map(itemgetter(1), g)
    ranges.append((group[0], group[-1]))

输出:

[(2, 5), (12, 17)]

编辑:该示例已经在文档中进行了解释,但也许我应该解释一下:

  

解决方案的关键是   差异与范围,以便   连续的数字都出现在同一个   基。

如果数据为:[2, 3, 4, 5, 12, 13, 14, 15, 16, 17] 然后groupby(enumerate(data), lambda (i,x):i-x)等同于以下内容:

groupby(
    [(0, 2), (1, 3), (2, 4), (3, 5), (4, 12),
    (5, 13), (6, 14), (7, 15), (8, 16), (9, 17)],
    lambda (i,x):i-x
)

lambda函数从元素值中减去元素索引。因此,当您在每个项目上应用lambda时。您将获得groupby的以下键:

[-2, -2, -2, -2, -8, -8, -8, -8, -8, -8]

groupby通过相等的键值对元素进行分组,因此前4个元素将组合在一起,依此类推。

我希望这会让它更具可读性。

python 3版本可能对初学者有用

首先导入所需的库

from itertools import groupby
from operator import itemgetter

ranges =[]

for k,g in groupby(enumerate(data),lambda x:x[0]-x[1]):
    group = (map(itemgetter(1),g))
    group = list(map(int,group))
    ranges.append((group[0],group[-1]))

答案 1 :(得分:24)

版本4.0中添加了

more_itertools.consecutive_groups

<强>演示

import more_itertools as mit


iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
[list(group) for group in mit.consecutive_groups(iterable)]
# [[2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [20]]

<强>代码

应用此工具,我们创建一个发现连续数字范围的生成器函数。

def find_ranges(iterable):
    """Yield range of consecutive numbers."""
    for group in mit.consecutive_groups(iterable):
        group = list(group)
        if len(group) == 1:
            yield group[0]
        else:
            yield group[0], group[-1]


iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
list(find_ranges(iterable))
# [(2, 5), (12, 17), 20]

source实现模拟classic recipe(由@Nadia Alramli演示)。

注意:more_itertools是可通过pip install more_itertools安装的第三方软件包。

答案 2 :(得分:15)

我发现“天真”的解决方案至少有点可读。

x = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 22, 25, 26, 28, 51, 52, 57]

def group(L):
    first = last = L[0]
    for n in L[1:]:
        if n - 1 == last: # Part of the group, bump the end
            last = n
        else: # Not part of the group, yield current group and start a new
            yield first, last
            first = last = n
    yield first, last # Yield the last group


>>>print list(group(x))
[(2, 5), (12, 17), (22, 22), (25, 26), (28, 28), (51, 52), (57, 57)]

答案 3 :(得分:13)

假设您的列表已排序:

>>> from itertools import groupby
>>> def ranges(lst):
    pos = (j - i for i, j in enumerate(lst))
    t = 0
    for i, els in groupby(pos):
        l = len(list(els))
        el = lst[t]
        t += l
        yield range(el, el+l)


>>> lst = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17]
>>> list(ranges(lst))
[range(2, 6), range(12, 18)]

答案 4 :(得分:8)

这里应该有用,不需要任何导入:

def myfunc(lst):
    ret = []
    a = b = lst[0]                           # a and b are range's bounds

    for el in lst[1:]:
        if el == b+1: 
            b = el                           # range grows
        else:                                # range ended
            ret.append(a if a==b else (a,b)) # is a single or a range?
            a = b = el                       # let's start again with a single
    ret.append(a if a==b else (a,b))         # corner case for last single/range
    return ret

答案 5 :(得分:6)

请注意,使用groupby的代码无法在Python 3中使用,因此请使用此代码。

for k, g in groupby(enumerate(data), lambda x:x[0]-x[1]):
    group = list(map(itemgetter(1), g))
    ranges.append((group[0], group[-1]))

答案 6 :(得分:3)

这不使用标准函数 - 它只是对输入进行了说明,但它应该可以工作:

def myfunc(l):
    r = []
    p = q = None
    for x in l + [-1]:
        if x - 1 == q:
            q += 1
        else:
            if p:
               if q > p:
                   r.append('%s-%s' % (p, q))
               else:
                   r.append(str(p))
            p = q = x
    return '(%s)' % ', '.join(r)

请注意,它要求输入仅按升序包含正数。您应该验证输入,但为清楚起见,省略了此代码。

答案 7 :(得分:1)

这是我想出的答案。我正在为其他人编写代码来理解,所以我对变量名和注释都很啰嗦。

首先是一个快速帮助函数:

def getpreviousitem(mylist,myitem):
    '''Given a list and an item, return previous item in list'''
    for position, item in enumerate(mylist):
        if item == myitem:
            # First item has no previous item
            if position == 0:
                return None
            # Return previous item    
            return mylist[position-1] 

然后是实际代码:

def getranges(cpulist):
    '''Given a sorted list of numbers, return a list of ranges'''
    rangelist = []
    inrange = False
    for item in cpulist:
        previousitem = getpreviousitem(cpulist,item)
        if previousitem == item - 1:
            # We're in a range
            if inrange == True:
                # It's an existing range - change the end to the current item
                newrange[1] = item
            else:    
                # We've found a new range.
                newrange = [item-1,item]
            # Update to show we are now in a range    
            inrange = True    
        else:   
            # We were in a range but now it just ended
            if inrange == True:
                # Save the old range
                rangelist.append(newrange)
            # Update to show we're no longer in a range    
            inrange = False 
    # Add the final range found to our list
    if inrange == True:
        rangelist.append(newrange)
    return rangelist

示例运行:

getranges([2, 3, 4, 5, 12, 13, 14, 15, 16, 17])

返回:

[[2, 5], [12, 17]]

答案 8 :(得分:1)

import numpy as np

myarray = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
sequences = np.split(myarray, np.array(np.where(np.diff(myarray) > 1)[0]) + 1)
l = []
for s in sequences:
    if len(s) > 1:
        l.append((np.min(s), np.max(s)))
    else:
        l.append(s[0])
print(l)

输出:

[(2, 5), (12, 17), 20]

答案 9 :(得分:1)

我认为这种方式比我在这里看到的任何答案都简单(编辑:根据 Pleastry 的评论修复):

data = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]

starts = [x for x in data if x-1 not in data and x+1 in data]
ends = [x for x in data if x-1 in data and x+1 not in data and x not in starts]
singles = [x for x in data if x-1 not in data and x+1 not in data]
list(zip(starts, ends)) + singles

输出:

[(2, 5), (12, 17), 20]

答案 10 :(得分:0)

使用numpy +理解列表:
使用numpy diff函数,可以识别其差异不等于1的后续输入向量条目。需要考虑输入向量的开始和结束。

import numpy as np
data = np.array([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])

d = [i for i, df in enumerate(np.diff(data)) if df!= 1] 
d = np.hstack([-1, d, len(data)-1])  # add first and last elements 
d = np.vstack([d[:-1]+1, d[1:]]).T

print(data[d])

输出:

 [[ 2  5]   
  [12 17]   
  [20 20]]

注意:省略了应该区别对待个别号码的请求(作为个人而非范围返回)。这可以通过进一步后处理结果来实现。通常这会使事情变得更加复杂而不会获得任何好处。

答案 11 :(得分:0)

一个没有额外导入的简短解决方案。它接受任何可迭代的,排序未排序的输入,并删除重复的项目:

def ranges(nums):
    nums = sorted(set(nums))
    gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e]
    edges = iter(nums[:1] + sum(gaps, []) + nums[-1:])
    return list(zip(edges, edges))

示例:

>>> ranges([2, 3, 4, 7, 8, 9, 15])
[(2, 4), (7, 9), (15, 15)]

>>> ranges([-1, 0, 1, 2, 3, 12, 13, 15, 100])
[(-1, 3), (12, 13), (15, 15), (100, 100)]

>>> ranges(range(100))
[(0, 99)]

>>> ranges([0])
[(0, 0)]

>>> ranges([])
[]

这与@ dansalmo&#39; s solution相同,我发现它很神奇,虽然有点难以阅读和应用(因为它没有作为功能提供)。

请注意,它可以轻松修改以吐出&#34;传统&#34;开放范围[start, end),例如改变return语句:

    return [(s, e+1) for s, e in zip(edges, edges)]

我从another question复制了这个答案,该答案被标记为此复制品的副本,目的是让它更容易找到(在我刚刚再次搜索此主题之后,首先在此处查找问题,不满意给出的答案)。

答案 12 :(得分:0)

使用groupby中的countitertools给我们提供了一个简短的解决方案。这个想法是,索引和值之间的差异将以递增的顺序保持不变。

为了跟踪索引,我们可以使用itertools.count,它使代码更干净,就像使用enumerate

from itertools import groupby, count

def intervals(data):
    out = []
    counter = count()

    for key, group in groupby(data, key = lambda x: x-next(counter)):
        block = list(group)
        out.append([block[0], block[-1]])
    return out

一些示例输出:

print(intervals([0, 1, 3, 4, 6]))
# [[0, 1], [3, 4], [6, 6]]

print(intervals([2, 3, 4, 5]))
# [[2, 5]]

答案 13 :(得分:0)

Mark ByersAndrea AmbuSilentGhostNadia Alramlitruppo的版本既简单又快速。 “ truppo”版本鼓励我编写一个版本,该版本在处理除1以外的步长时保留了相同的敏捷行为(并且以单例元素的形式列出,在给定步长下步长不超过1步)。它被赋予here

>>> list(ranges([1,2,3,4,3,2,1,3,5,7,11,1,2,3]))
[(1, 4, 1), (3, 1, -1), (3, 7, 2), 11, (1, 3, 1)]

答案 14 :(得分:0)

不是最好的方法,但这是我的2美分

def getConsecutiveValues2(arr): 
    x = ""
    final = []
    end = 0
    start = 0
    for i in range(1,len(arr)) :
        if arr[i] - arr[i-1] == 1 :
            end = i
        else :
            print(start,end)
            final.append(arr[start:end+1])
            start = i
        if i == len(arr) - 1 :
            final.append(arr[start:end+1])
    return final

x = [1,2,3,5,6,8,9,10,11,12]
print(getConsecutiveValues2(x))

>> [[1, 2, 3], [5, 6], [8, 9, 10, 11]]

答案 15 :(得分:0)

此实现适用于规则或不规则步骤

我需要实现相同的目标,但在步骤可能不规则的情况下略有不同。这是我的实现

def ranges(l):
    if not len(l):
        return range(0,0)
    elif len(l)==1:
        return range(l[0],l[0]+1)
    # get steps
    sl    = sorted(l)
    steps = [i-j for i,j in zip(sl[1:],sl[:-1])]
    # get unique steps indexes range
    groups = [[0,0,steps[0]],]
    for i,s in enumerate(steps):
        if s==groups[-1][-1]:
            groups[-1][1] = i+1
        else:
            groups.append( [i+1,i+1,s] )
            g2 = groups[-2]
            if g2[0]==g2[1]:
                if sl[i+1]-sl[i]==s:
                    _=groups.pop(-2)
                    groups[-1][0] = i
    # create list of ranges 
    return [range(sl[i],sl[j]+s,s) if s!=0 else [sl[i]]*(j+1-i) for i,j,s in groups]

这是一个例子

from timeit import timeit

# for regular ranges
l = list(range(1000000))
ranges(l)
>>> [range(0, 1000000)]
l = list(range(10)) + list(range(20,25)) + [1,2,3]
ranges(l)
>>> [range(0, 2), range(1, 3), range(2, 4), range(3, 10), range(20, 25)]
sorted(l);[list(i) for i in ranges(l)]
>>> [0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24]
>>> [[0, 1], [1, 2], [2, 3], [3, 4, 5, 6, 7, 8, 9], [20, 21, 22, 23, 24]]

# for irregular steps list
l = [1, 3, 5, 7, 10, 11, 12, 100, 200, 300, 400, 60, 99, 4000,4001]
ranges(l)
>>> [range(1, 9, 2), range(10, 13), range(60, 138, 39), range(100, 500, 100), range(4000, 4002)]

## Speed test
timeit("ranges(l)","from __main__ import ranges,l", number=1000)/1000
>>> 9.303160999934334e-06