我有一个这样的列表:
a = [1, 2, 3, 4, 5, 8, 9, 10, 11, 15, 16, 17]我希望得到如下结果:
b = [1-5, 8-11, 15-17]因为在我的列表a中,我有来自1 to 5, 8 to 11的序列号,然后是15 to 17。
我应该如何在Python中做到这一点?
发布于 2019-02-04 13:27:39
使用itertools.groupby作为described here,但@luca稍作更改
import itertools
def to_ranges(iterable):
iterable = sorted(set(iterable))
for key, group in itertools.groupby(enumerate(iterable),
lambda t: t[1] - t[0]):
group = list(group)
yield group[0][1], group[-1][1]
x = [1, 2, 3, 4, 5, 8, 9, 10, 11, 15, 16, 17]
print( list(to_ranges(x)))输出:
[(1, 5), (8, 11), (15, 17)]发布于 2019-02-04 13:42:44
def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
lst = [1, 2, 3, 4, 5, 8, 9, 10, 11, 15, 16, 17]
x=range_extract(lst)
print(list(x))
# output : [(1, 5), (8, 11), (15, 17)]https://stackoverflow.com/questions/54510479
复制相似问题