使用for循环删除列表中的项目 [英] Delete item in a list using a for-loop
本文介绍了使用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
。
这篇关于使用for循环删除列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文