在迭代贪婪算法时从元组列表中删除元组-python

时间:2018-09-05 17:25:03

标签: python list tuples

我正在尝试编写一个贪婪算法,并且有一个元组列表:

cow_list = [('Betsy',9),('Henrietta',9),('Herman',7),('Oreo',6),('Millie',5),('Maggie' ,3),('Moo Moo',3),('Milkshake',2),('Lola',2),('Florence',2)]

我正在尝试遍历列表:

def greedy_cow_transport(cow_list, maxWeight):
transport_name = []
taken_transport = []
not_taken = []
transport_weight = []
for i in range(len(cow_list)):
    total_weight = sum(transport_weight)
    if (total_weight+cow_list[i][1]) <= maxWeight:
        transport_name.append(cow_list[i][0])
        transport_weight.append(cow_list[i][1])
        total_weight += cow_list[i][1]
    elif (total_weight+cow_list[i][1]) > maxWeight:
        taken_transport.append(cow_list[i][0])            

我想做的是,如果> maxWeight,则删除列表中的第一个元组,以便for循环可以重新开始该过程,而无需使用该第一个元组。

所以我希望最终结果是:

transport_name = [['Betsy'],['Henrietta'],['Herman','Maggie'],['Herman','Moo Moo'],['Herman','奶昔']等,其中所有值的总和为<10。

如果我的问题没有道理,请告诉我。

1 个答案:

答案 0 :(得分:0)

一种非常临时的方法,

def greedy_cow_transport(cow_list, maxWeight):
    transport_name = []
    taken_transport = []
    not_taken = []
    transport_weight = []
    for i in range(len(cow_list)):
        # Store an initial element
        temp_name.append(cow_list[i][0])
        temp_weight.append(cow_list[i][1])
        total_weight = sum(temp_weight)

        # Iterate on all the elements to the right
        for j in range(i, len(cow_list)):
            if (total_weight + cow_list[j][1])<= maxWeight:
                temp_name.append(cow_list[j][0])
                temp_weight.append(cow_list[j][1])
                total_weight = sum(temp_weight)
            else:
                taken_temp_transport.append(cow_list[j][0])

        transport_name.append(temp_name)
        transport_weight.append(temp_weight)
        taken_transport.append(taken_temp_transport)