根据集合最大长度缩短一些列表,将多余的列表移动到新列表

Sim*_*erg 5 python

我有N个不同长度的列表.这些列表包含要在UI中显示的项目,并且我的最大UI预算为X.任何多余的项目都会进入下拉菜单.我需要做的是将列表中的项目移动到它们的"溢出"等效项中,以便所有列表的总长度等于或小于最大长度.我想确保没有列出的列表少于必要的列表,并且它们最终会尽可能接近相等的长度.例:

我有三个列表l1=range(10),l2=range(15)和,l3=range(20)maxLength=40.我需要从中得到的是l1l2保持原样并l3缩短为15项,因为10 + 15 + 15 = 45.如果l1=range(15)不是,我应该结束了两个清单13项和一个14.

目前,我有一个使用while循环来实现此功能的函数,如下所示:

def shortenLists(maxLength, *input_lists):
    overflows = [[] for n in input_lists]

    while sum(len(l) for l in input_lists) > maxLength:
        longestList = max(input_lists, key=len)
        index = input_lists.index(longestList)
        overflows[index].append(longestList.pop())

    [o.reverse() for o in overflows]
    return input_lists, overflows
Run Code Online (Sandbox Code Playgroud)

这似乎基本上可行,但我不特别喜欢使用while循环这样的事情; 似乎要弄清楚要从每个列表中删除多少项目应该相对简单.此方法还依赖于使用list.index()方法查找输入中最长列表的索引,以便将项添加到正确的溢出缓冲区,这看起来有点像黑客.

该函数返回两个列表的元组,其中裁剪的输入列表按顺序排列,溢出缓冲区按相同的顺序排列.我不确定这是否是最好的方法,最好将它们压缩,以便它返回((列表,溢出),(列表,溢出)).

per*_*eal 0

您的代码略有不同:

def shortenLists(maxLength, *input_lists):
    item_per_list = maxLength / len(input_lists)
    overflows = []
    for (i, l) in enumerate(input_lists):
        overflows.append(l[item_per_list:])
        l[item_per_list:] = []
    return input_lists, overflows
Run Code Online (Sandbox Code Playgroud)