python访问数组错误

时间:2013-09-12 10:24:49

标签: python arrays multidimensional-array

我正在进行一项任务,但是几行不断给我一些我无法理解的错误

pick=0
final=0
while True:

    if (min_weight>0):

        if (sort_ratio[pick]["Weight"]<min_weight):
            final = final + sort_ratio[pick]["Cost"]
            min_weight = min_weight - sort_ratio[pick]["Weight"]

        if (sort_ratio[pick]["Weight"]>min_weight):
            pick = pick + 1

        if (min_weight == 0):
            print (final)
            return 

唯一的问题是当程序通过“pick = pick + 1”时它会停止并给出“index out of range”错误。

我没有使用增量方法,而是尝试使用

编辑数组
sort_ratio.remove(sort_ratio[0]);

但它给了我“不能解释为整数问题”

现在代码

from operator import itemgetter
import math

raw_input=input;

test_case = int(raw_input());


for inp1 in range (test_case):
    min_weight = int(raw_input());
    candy_types = int(raw_input());
    candy = [];

for inp2 in range (candy_types):

    can_weight,can_cost = map(int,raw_input().split());

    ratio_candy = (can_cost / int(can_weight));

    candy.extend([{"Cost": can_cost, "Ratio": ratio_candy, "Weight": can_weight}]);

sort_ratio = sorted ( candy, key=itemgetter('Ratio'));
pick = 0;
final = 0;

while True:

    if (min_weight>0):

        if (sort_ratio[pick]["Weight"]<min_weight):
            final = final + sort_ratio[pick]["Cost"]
            min_weight = min_weight - sort_ratio[pick]["Weight"]
            print (final)
            print (min_weight)

        if (sort_ratio[pick]["Weight"]>min_weight):
            pick = pick + 1

        if (min_weight==0):
            print (final)
            break

0 个答案:

没有答案