14 Jun 2023

Code_Tips

Code_Tips

Linux_DebugNotes_05

image

How to turn multi-dim ndarray of ndarray into list: numpy.matrix

temp = array(array([...]), array([...])...)
x = np.matrix(temp); 
x.tolist()

Python List Iteration Removal

Suppose you have a list of integers and you want to remove all elements that are less than 5:

nums = [1, 4, 6, 3, 7, 2, 8]
for num in nums[:]:  # Create a shallow copy for iteration
    if num < 5:
        nums.remove(num)

This code attempts to remove elements less than 5 directly while iterating over the list. The problem is that removing elements shifts the positions of the subsequent elements, causing the loop to skip over elements immediately following a removed element. As a result, some elements that should be removed may not be, leading to incorrect final lists.

  • a. Iterate Over a Copy of the List You can iterate over a copy of the list, so modifications do not affect the iteration:
    nums = [1, 4, 6, 3, 7, 2, 8]
    for num in nums[:]:  # Create a shallow copy for iteration
      if num < 5:
          nums.remove(num)
    
  • b. Iterate Backwards Using Indices Another approach is to iterate over the list in reverse order by indices, so removing elements doesn’t affect the iteration of the remaining elements:
    nums = [1, 4, 6, 3, 7, 2, 8]
    for i in range(len(nums) - 1, -1, -1):
      if nums[i] < 5:
          del nums[i]
    

Tags:
0 comments