我有一堆数字,请说以下内容:
1 2 3 4 6 7 8 20 24 28 32
那里提供的信息可以用 Python 表示为范围:
[range(1, 5), range(6, 9), range(20, 33, 4)]
在我的输出中我会写1..4, 6..8, 20..32..4
,但这只是一个演示问题。
另一个答案 https://stackoverflow.com/a/4629241展示了如何对连续范围执行此操作。我不明白我如何能够轻松地为上面这样的跨步范围做到这一点。有类似的技巧吗?
这是解决该问题的直接方法。
def get_ranges(ls):
N = len(ls)
while ls:
# single element remains, yield the trivial range
if N == 1:
yield range(ls[0], ls[0] + 1)
break
diff = ls[1] - ls[0]
# find the last index that satisfies the determined difference
i = next(i for i in range(1, N) if i + 1 == N or ls[i+1] - ls[i] != diff)
yield range(ls[0], ls[i] + 1, diff)
# update variables
ls = ls[i+1:]
N -= i + 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)