使用for循环删除列表中的项目

问题描述:

我有一个包含主题的数组,每个主题都有连接时间。我想比较列表中的每个主题。如果有两个相同的主题,我想添加两个主题的时间,并且还想删除第二主题信息(主题名称和时间)。

I have an array with subjects and every subject has connected time. I want to compare every subjects in the list. If there are two of the same subjects, I want to add the times of both subjects, and also want to delete the second subject information (subject-name and time).

但是如果我删除该项目,列表变短,并且我得到一个超出范围的错误。我尝试使用subjectlegth-1缩短列表,但这也不起作用。

But If I delete the item, the list become shorter, and I get an out-of-range-error. I tried to make the list shorter with using subjectlegth-1, but this also don't work.

   ...
   subjectlegth = 8
   for x in range(subjectlength):
        for y in range(subjectlength):
            if subject[x] == subject[y]:
                if x != y:
                    #add
                    time[x] = time[x] + time[y]
                    #delete
                    del time[y]
                    del subject[y]
                    subjectlength = subjectlength - 1


向后迭代,如果可以:

for x in range(subjectlength - 1, -1, -1):

,同样 y