假设我有一个排序列表:
a=[1,2,3,4,5,6,10,11,12,13,14,15,16,20,23,25,26,27]
如何在a
中得到子序列,如:
[(1,2,3,4,5,6),(10,11,12,13,14,15,16),20,23,(25,26,27)]
答案 0 :(得分:0)
a=[1,2,3,4,5,6,10,11,12,13,14,15,16,20,23,25,26,27]
lst = []
last = None
for item in a:
if last is None:
current = [item]
elif item - last == 1:
current.append(item)
else:
if 1 == len(current):
lst.append(current[0])
else:
lst.append(tuple(current))
current = [item]
last = item
lst.append(tuple(current))
print(lst)
输出:
[(1, 2, 3, 4, 5, 6), (10, 11, 12, 13, 14, 15, 16), 20, 23, (25, 26, 27)]