Opps_0
Opps_0

Reputation: 438

How to remove an item from a list of Path?

I have a list of lists, where I do have the path of all my training images, like the below one.

from pathlib import Path
image_list = [[Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],

 [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],

  [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0733_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0733_Img_Na__Ma_F_.png')]
  ]

Now, I want to remove one item from the list based on a portion of the path (specifically, based on the last part of the path). Say, I want to remove one element from the list whose name starts with Image_033_S_0733....

I was trying to

final_list = []
for sub_list in listA:
   for sub_sub_list in sub_list:
       if "Image_033_S_0733" not in sub_sub_list.name:
           final_list.append(sub_sub_list)

I am getting a flat list instead of a list of lists. The shape of the image_list is (77, 2). The expected output is (after removing the item from the list of lists) (76, 2) but I am getting (228, ).

Is it possible to remove an item from a list of PosixPath?

Upvotes: 0

Views: 642

Answers (1)

Barmar
Barmar

Reputation: 781721

Use the .name attribute to get the filename from a Path object.

So replace the condition in your loop or list comprehension with:

'Image_044_S' not in item.name

To get a nested loop over results, use nested list comprehensions.

final_list = [
    [item for item in sub_list if "Image_033_S_0733" not in item.name]
    for sub_list in image_list]

Upvotes: 2

Related Questions