Home > Back-end >  Create a new array list for all matching filenames in ''main'' array
Create a new array list for all matching filenames in ''main'' array

Time:07-07

I have code in Python that loops through an directory of images that returns an array 105 images. Now I need it to go through the array and find the matching images by name Example: Mainlist = [Image_Sun_01, Image_Sun_02, Image_Moon_01] and I want it create a seperate list for each matching image like so:

List_01 = [Image_Sun_01, Image_Sun_02]
List_02 = [Image_Moon_01]

What is the best way to do this?

Edit:

To clarify I want it to match the words with each other so "Sun" goes with "Sun" into a list and "Moon" with "Moon" into a new list

CodePudding user response:

From the sample data shown in the question it appears that the "key" is part of a filename within two underscore characters. If that is the case then one idea would be to build a dictionary which is keyed on those tokens. Something like this:

Mainlist = ['Image_Sun_01.cr2', 'Image_Sun_02.jpg', 'Image_Moon_01.raw']

result = {}

for image in Mainlist:
    key = image.split('_')[1]
    result.setdefault(key, []).append(image)

print(result)

Output:

{'Sun': ['Image_Sun_01.cr2', 'Image_Sun_02.jpg'], 'Moon': ['Image_Moon_01.raw']}

Note:

Subsequently, access to 'Sun' or 'Moon' images is trivial

CodePudding user response:

I have added data to your Mainlist to check the result of my proposed code and get 3 different size lists in output.

import re

Mainlist = ['Image_Sun_01', 'Image_Sun_02', 'Image_Moon_01', 'Image_Moon_02', 'Image_Moon_03', 'Image_Earth_01']

prev_pattern = ''
nb = 0
for i in range(len(Mainlist)):
  new_pattern = re.search('[a-zA-Z\_] ', Mainlist[i]).group(0)
  if new_pattern != prev_pattern:
    nb =1
    prev_pattern = new_pattern
  if f"List_{nb:02d}" in globals():
    globals()[f"List_{nb:02d}"]  = [Mainlist[i]]
  else:  
    globals()[f"List_{nb:02d}"] = [Mainlist[i]]

print(List_01)
print(List_02)
print(List_03)

Output:

['Image_Sun_01', 'Image_Sun_02']
['Image_Moon_01', 'Image_Moon_02', 'Image_Moon_03']
['Image_Earth_01']
  • Related