Delete item in a list using a for-loop

前端 未结 5 1029
感情败类
感情败类 2021-01-13 17:35

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 ti

相关标签:
5条回答
  • 2021-01-13 17:55

    Iterate backwards, if you can:

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

    and similarly for y.

    0 讨论(0)
  • 2021-01-13 18:04

    Though a while loop is certainly a better choice for this, if you insist on using a for loop, one can replace the list elements-to-be-deleted with None, or any other distinguishable item, and redefine 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 the case of the 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 讨论(0)
  • 2021-01-13 18:08

    The best practice is to make a new list of the entries to delete, and to delete them after walking 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]
    
    0 讨论(0)
  • 2021-01-13 18:09

    An alternate way would be to create the subject and time lists anew, using a dict to sum up the times of recurring subjects (I am assuming subjects are strings i.e. hashable).

    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
    
    0 讨论(0)
  • 2021-01-13 18:14

    If the elements of subject are hashable:

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

    This will result in a dict with subject: time key-value pairs.

    0 讨论(0)
提交回复
热议问题