【发布时间】:2016-09-26 18:13:20
【问题描述】:
在other SO post 中,一位 Python 用户询问如何对连续数字进行分组,以便任何序列都可以仅由其开始/结束来表示,而任何落后者都将显示为单个项目。接受的答案非常适合连续序列。
我需要能够适应类似的解决方案,但对于可能(并非总是)具有变化增量的数字序列。理想情况下,我表示的方式还包括增量(这样他们就会知道是每 3、4、5、n 次)
参考原始问题,用户要求以下输入/输出
[2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20] # input
[(2,5), (12,17), 20]
我想要的是以下内容(注意:为了清楚起见,我写了一个元组作为输出,但 xrange 最好使用它的 step 变量):
[2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20] # input
[(2,5,1), (12,17,1), 20] # note, the last element in the tuple would be the step value
它还可以处理以下输入
[2, 4, 6, 8, 12, 13, 14, 15, 16, 17, 20] # input
[(2,8,2), (12,17,1), 20] # note, the last element in the tuple would be the increment
我知道xrange() 支持一个步骤,因此甚至可以使用其他用户答案的变体。我尝试根据他们在解释中写的内容进行一些编辑,但我无法得到我想要的结果。
对于不想点击原始链接的任何人,Nadia Alramli最初发布的代码是:
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])
【问题讨论】:
标签: python