python找出列表中的连续元素

习总 发布于 2013/04/22 17:54
阅读 1K+
收藏 1
比如:
[3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46]
怎么得到下面的结果呢?
[[3,7],[10,12],[15,17],[19,24],[42,46]]
加载中
1
骠骑将军
骠骑将军

非循环写法

a = [3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46]
a = a+[a[-1]]
b = [a[i]-a[i-1] for i in range(1,len(a))]
c = [i for i in range(len(b)) if b[i]!=1]
d = [-1]+c
e = [(a[d[i]+1],a[d[i+1]]) for i in range(len(d)-1)]
a.pop(-1)
print a
print e
结果

>>> ================================ RESTART ================================
>>> 
[3, 4, 5, 6, 7, 10, 11, 12, 15, 16, 17, 19, 20, 21, 22, 23, 24, 42, 43, 44, 45, 46]
[(3, 7), (10, 12), (15, 17), (19, 24), (42, 46)]
>>>

0
骠骑将军
骠骑将军
用循环读了写吧
0
Pongox
Pongox
set是无序的,很可能出问题的哦
习总
习总
哦,改过来了
0
Pongox
Pongox
#coding:utf-8
t1 = []
t2 = []
#在列表中添加了48以验证最后一个数不连续的情况
a = [3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46,48]
for x in a:
    t1.append(x)
    if x+1 not in a:
        t2.append([t1[0], t1[-1]])
        t1 = []
print t2
Pongox
Pongox
回复 @wyuan : 输出与题目的不一样,是因为我改了输入,多了个48。用骠骑将军的代码跑,结果也是和我一样的,呵呵。
wyuan
wyuan
输出结果是: [[3, 7], [10, 12], [15, 17], [19, 24], [42, 46], [48, 48]] 不过想法很好
返回顶部
顶部