如何根据阈值扩展整数列表?

2024-01-19

我在 python 中有一些整数列表:

[[2, 8, 10, 500, 502], [1, 4, 5, 401]]

如何根据列表中数字之间的差异将值扩展为连续范围,这样我会得到如下结果:

[[2, 3, 4, 5, 6, 7, 8, 9, 10, 500, 501, 502], [1, 2, 3, 4, 5, 401]]

那么,基本上,只有当列表中的项目之间的差异小于 100 时,才将一组数字扩展为完整范围?


虽然很丑,但试试这个:

def list_expand(x):
    new_list = []
    while True:
        if len(x) < 2:
            new_list.append(x[0])
            break

        m = min(x)
        x.remove(m)
        if abs(m - min(x)) < 100:
            new_list.extend(range(m, min(x)))
        else:
            new_list.append(m)
    return new_list

它通过了这些测试:

assert list_expand([99, 0, 198]) == range(0, 199)
assert list_expand([100, 0, 200]) == [0, 100, 200]
assert list_expand([2, 8, 10, 500, 502]) == range(2, 11) + range(500, 503)
assert list_expand([1, 4, 5, 401]) == range(1, 6) + [401]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据阈值扩展整数列表? 的相关文章

随机推荐