我有一个输入列表:
s = [1, 2, 3, 5, 6, 9, 10, 11]
我正在尝试将以下内容作为输出:
lows = [1, 5, 9]
highs = [3, 6, 11]
lows
列表包含列表中连续数字的所有子列表中的所有最低数量:[1, 2, 3], [5, 6], and [9, 10, 11]
。高点,反之亦然。
最简洁的方法是什么?我想知道itertools
中是否有可以做得很好的东西?
答案 0 :(得分:3)
>>> from itertools import groupby, count
>>> from operator import itemgetter
>>> s = [1, 2, 3, 5, 6, 9, 10, 11]
>>> ig = itemgetter(0, -1)
>>> lows, highs = zip(*(ig(list(g)) for k, g in groupby(s, lambda x, c=count(): x-next(c))))
>>> lows
(1, 5, 9)
>>> highs
(3, 6, 11)
答案 1 :(得分:2)
总有明显的手动方法:
s = [1, 2, 3, 5, 6, 9, 10, 11]
def runs(iterable):
iterator = iter(iterable)
start = end = next(iterator)
for item in iterator:
if item != end + 1:
yield (start, end)
start = item
end = item
yield (start, end)
lows, highs = zip(*runs(s))
lows
#>>> (1, 5, 9)
highs
#>>> (3, 6, 11)