在列表列表的索引处查找最大数的函数

2024-09-27 21:34:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个在线python课程,我被其中一个任务困住了。你知道吗

我有一个列表,下面是一个字符串和一个int,int代表一个权重,我有一个特定的权重限制10:

WeightLimit = 10
MyList = [['ItemOne','9'],['ItemTwo','4'],['ItemThree','7'],['ItemFour','2'], ,['ItemFive','1']]

我需要根据我的体重限制把这些物品移到一个新的清单上,而每一件新物品本质上都是一次送货。我要先送最重的东西。你知道吗

所以基本上ItemOne将是我第一次也是唯一一次交货,因为我现在的限额是1(10-9)。我的限制现在重置为10,因为我不能再提供了。我的下一次交货是第三项、第四项、第五项(7+2+1=10)。我的限制重置为10,因为我不能再提供了。我的最后一批货现在是第二批。你知道吗

我的输出是:

newList = [['ItemOne'],['ItemThree', 'ItemFour', 'ItemFive'], ['ItemTwo']]

到目前为止,我已经:

heaviest = 0
lightest = 10
name = ''
weightLimit = limit
outputList = []
loopList = []

for item in MyList:
    if int(item[1]) > heaviest:
        heaviest = int(item[1])
        name = item[0]
    elif int(item[1]) < lightest:
        lightest = int(item[1])

loopList.append(name)
weightLimit = weightLimit - heaviest

for item in myList:
    if name == item[0]:
        MyList.remove(item)

if lightest > weightLimit:
    weightLimit = 10
    outputList.append(loopList)
    loopList = []

所以这基本上是通过,找到最重的项目,和最轻的项目。如果最轻的项大于我的剩余限制,则所有项都将重置,并且这些项将添加到输出列表中。你知道吗


Tags: name列表ifitemint重置权重mylist

热门问题