Home > Software engineering >  Transform nested for-loops to list comprehension
Transform nested for-loops to list comprehension

Time:03-04

I have the following code:

  files_to_upload = []
  for file_name in ignore_list:
      for file_path in files_not_in_Azure:
          if file_name in file_path:
              files_to_upload.append(file_path)

How can this be written in one line using a list comprehension?

CodePudding user response:

You can do the following, using itertools.product:

from itertools import product
files_to_upload = [file_path for file_path, file_name in product(ignore_list, files_not_in_Azure) if file_name in file_path]

Note that using multiple for clauses is more verbose here. (Some also consider it to be poor style.)

CodePudding user response:

[
    files_to_upload.append(file_path) 
    for file_paths in 
    [
        [
            file_path
            for file_path
            in files_not_in_Azure
            if file_name in file_path
        ]
        for file_name in ignore_list
    ]
    for file_path in file_paths
]

but as @BrokenBenchmark said, making a one-liner will make it less readable.

Your ignore_list might also be misnamed if those are the files you do want to upload.

As for complexity, you should consider finding a way to directly search for the filenames instead of iterating over both lists with a fuzzy search. Something along the lines of

ignore_set = set(ignore_list)
files_to_upload = filter(lambda filepath:os.path.basename(filepath) in ignore_set, files_not_in_Azure)
  • Related