Delete an item in a list using a for-loop

I have an array with items, and each item has a connection time. I want to compare all the items in the list. If there are two identical topics, I want to add time for both items, and I also want to delete the second subject information (name and time).

But if I delete the item, the list becomes shorter and I get an error out of range. I tried to make the list shorter using subjectlegth-1, but this also does not 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 
+4
source share
5 answers

Iterate back if you can:

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

and similarly for y .

+8
source

If subject elements are hashed:

 finalinfo = {} for s, t in zip(subject, time): finalinfo[s] = finalinfo.get(s, 0) + t 

This will result in an expression using subject: time key-value pairs.

+8
source

The best practice is to create a new list of deleted records and delete them after going through the list:

 to_del = [] subjectlength = 8 for x in range(subjectlength): for y in range(x): if subject[x] == subject[y]: #add time[x] = time[x] + time[y] to_del.append(y) to_del.reverse() for d in to_del: del subject[d] del time[d] 
+6
source

An alternative way would be to re-create the topic and timelists, using dict to summarize the time of repeated items (I assume that the subjects are strings, i.e. hashed).

 subjects=['math','english','necromancy','philosophy','english','latin','physics','latin'] time=[1,2,3,4,5,6,7,8] tuples=zip(subjects,time) my_dict={} for subject,t in tuples: try: my_dict[subject]+=t except KeyError: my_dict[subject]=t subjects,time=my_dict.keys(), my_dict.values() print subjects,time 
+2
source

Although a while is by far the best choice for this, if you insist on using a for loop, you can replace the list items to be removed with None or any other distinguishable element, and override the list after the for loop. The following code removes even elements from a list of integers:

 nums = [1, 1, 5, 2, 10, 4, 4, 9, 3, 9] for i in range(len(nums)): # select the item that satisfies the condition if nums[i] % 2 == 0: # do_something_with_the(item) nums[i] = None # Not needed anymore, so set it to None # redefine the list and exclude the None items nums = [item for item in nums if item is not None] # num = [1, 1, 5, 9, 3, 9] 

In case of a question in this post:

 ... for i in range(subjectlength - 1): for j in range(i+1, subjectlength): if subject[i] == subject[j]: #add time[i] += time[j] # set to None instead of delete time[j] = None subject[j] = None time = [item for item in time if item is not None] subject = [item for item in subject if item is not None] 
0
source

All Articles