如何获取列表的最小整数值

时间:2015-03-04 21:01:25

标签: python list

我有一个名为weight的变量,它是一个充满int值的列表。在每轮循环之后,我想要隐藏当前的最小值,或者将其替换为' o'这样我就可以找到下一个最小值的值。例如,weight = [4,2,4,1,3,5,6,2,3]会变成[4, 2, 4, 'o', 3, 5, 6, 2, 3] ..我所遇到的问题是当循环第二次运行时它会生成一个错误,因为添加了' o。

def greedyMinWt():
    weight = [4,2,4,1,3,5,6,2,3]
    value = [7,9,9,8,5,8,3,5,2]
    itemPick = [4,2,4,1,3,5,6,2,3]
    val = 0
    weightCount = 0
    itemCounter = 0
    valueCount = 0
    totalWeight = 0
    totalValue = 0
    weightInput = -1
    pickedItems = []
    n=0
    capacity = 17

    print('Itm|' + ' Wt|' + ' Val' )
    for num in range(0,len(weight)):
        print('(' + str(num+1) + ')' + '\t ' + str(weight[num]) + '\t ' + str(value[num]))
    print('\nSolve by greedy min wt:')
    while totalWeight < capacity:
         minWt = min(weight)
         val = value[weight.index(min(weight))]
         totalWeight += minWt
         totalValue += val
         slackWt = capacity - totalWeight
         'Need to fix this so it will print out the correct pick'

         if totalWeight > capacity:
            totalWeight-= min(weight)
            totalValue -=val
            print('\n__Greedy min weight __ \nItems Picked: '+ ' #' + ' #'.join(pickedItems))
            print('Feasible' + '\t' + 'WeightCount:' + str(totalWeight) + '\tValueCount:' + str(totalValue) + '\n' + 'The capacity is:' + str(capacity))
            return None
         print('pick =' + str(weight.index(minWt)+1) + ' accumWt=' + str(totalWeight) + ' slackWt=' + str(slackWt) + ' accumVal=' + str(totalValue))
         weight[weight.index(min(weight))] = 'o'
         print(weight)

2 个答案:

答案 0 :(得分:2)

使用列表推导来提取整数:

min_weight = min([i for i in weight if str(i).isdigit()])

答案 1 :(得分:0)

此示例循环遍历您的weight列表并提取最小值。它将此值放入min_weights列表中。找到的值然后更改为o

注意:如果存在重复的最小值,则使用.index()将第一个最小值替换为o。下一次循环,将找到副本,添加到另一个列表,然后更改为o

weight = [4,2,4,1,3,5,6,2,3]

min_weights = []
for x in range(len(weight)):
    min_weights.append(min(weight))
    weight[weight.index(min(weight))] = 'o'

print min_weights
print weight

这输出以下内容:

[1, 2, 2, 3, 3, 4, 4, 5, 6]   # This is your minimum weights
['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o']   # This is your weight list after the loop is complete