如何基于阈值扩展整数列表? [英] How to expand a list of integer based on a threshold?

查看:95
本文介绍了如何基于阈值扩展整数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some lists of integers in python:

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

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

How would I expand the values into continuous ranges based on the difference between the numbers in the list so I get something like this:

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

因此,基本上,如果列表中各项之间的差小于100,则仅将一组数字扩展到整个范围?

So, basically, only expand a set of numbers into a full range if the difference between the items in the list is less than 100?

推荐答案

这很丑,但是尝试一下:

It's ugly, but try this:

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]

这篇关于如何基于阈值扩展整数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆