Delete item in a list using a for-loop

前端 未结 5 1195
感情败类
感情败类 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 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]
    

提交回复
热议问题