简体   繁体   English

Python:如何将整数列表转换为整数的嵌套列表,其中每个嵌套列表的 max-min 永远不会超过 X?

[英]Python: How to convert a list of integers into nested lists of integers where max-min for each nested list never exceeds X?

I'm actually having a hard time explaining this problem.我实际上很难解释这个问题。 The title ask for this:标题要求这个:

limit = 100
l = [1, 2, 4, 9, 33, 77, 85, 100, 151, 304, 405, 407, 499]

do_something(l, limit)

[
[1,2,4,9,33,77,85,100],
[151],
[304],
[405, 407, 499]
]

But that was just one step in my thought process.但这只是我思考过程中的一步。 Truth is, I need this result:事实是,我需要这个结果:

limit = 100
l = [1, 2, 4, 9, 33, 77, 85, 100, 151, 304, 405, 407, 499]

do_something(l, limit)

[
range(1,101),
range(151,152),
range(304,305),
range(405,500)
]

Notice range never exceeds the limit of 100, and its creating a list out of ints from l that fall within the limit (starting from l[0] and resetting any time limit is exceeded).注意范围永远不会超过 100 的限制,它会从l中的 int 中创建一个列表,这些整数在限制范围内(从l[0]开始并超过重置任何时间限制)。 I am brainstorming ideas over here, but everything I can think of iterates over my list several times.我在这里集思广益,但我能想到的一切都在我的列表中重复了好几次。 If that's necessary so be it, but I'd like to be a bit more efficient than that.如果有必要,那就这样吧,但我想比这更有效率。

Thanks for any help谢谢你的帮助

Loop through the sorted list.遍历排序列表。 Each time you start a group, save the first value of the range in one variable.每次开始组时,将范围的第一个值保存在一个变量中。 Then as you step through the list, update the last value of the range to the current element.然后,当您逐步浏览列表时,将范围的最后一个值更新为当前元素。 Whenever the element exceeds first+limit , you start a new range.每当元素超过first+limit时,您就会开始一个新范围。

def do_something(l, limit):
    if l == []:
        return []
    end = l[0] + limit
    result = []
    first = last = l[0]
    for i in sorted(l):
        if i < end:
            last = i
        else:
            result.append(range(first, last + 1))
            first = last = i
            # reset the limit
            end = i + limit
    # append the last sublist
    result.append(range(first, last+1))
    return result

you also can emplement such logic:你也可以实现这样的逻辑:

def do_something(l,limit):
    res = []
    x = y = 0
    for y in range(len(l)):
        if y==len(l)-1 or l[x] + limit <= l[y+1]:
            res.append(range(l[x], l[y]+1))
            x = y + 1
    return res

do_something(l,limit)

>>> out
'''
[range(1, 101), range(151, 152), range(304, 305), range(405, 500)]

Why dont you try dictionaries to store list of values within limit.为什么不尝试使用字典来存储限制范围内的值列表。 In this implementation, list is not necessarily to be sorted.在这个实现中,列表不一定要排序。

limit = 100
ranged_list = {}
for col in l:
  lst = ranged_list.get((col-1) // limit, [])
  lst.append(col)
  ranged_list[(col-1) // limit] = lst

print(list(ranged_list.values()))

>>> [
[1, 2, 4, 9, 33, 77, 85,100], 
[151],
[304],
[405, 407, 499]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM