简体   繁体   中英

Avoid nested loops using list-comprehension

I'm wondering if this is a good idea to avoid nested loops using List Comprehension in the case bellow

Imagine the following list of names in a config.py file

# config.py
NAME_LIST = [
    'name1',
    'name2',
    (...)
]

I'm using this list of names to go though multiple different directories, and for each of the files I find, I read the content of the files and process data.

This is my actual code:

import config

def foo():

    for w in config.NAME_LIST:
        folder = "/data/test/{name}/in".format(name=w)
        files = list_files(folder) # return a list of files found in folder

        for f in files:
            content = read_file(folder, f) # read files content
            # (... do some stuff to process data)

I really want to avoid a nested loop to keep the code as flat as possible.

I tried to approach this using List Comprehension but not sure this is the best solution as I don't want it to return anything.

Here is what I've done:

import config

def foo():

    def _process(f):
        """function called from list comprehension to avoid doing nested loops"""
        content = read_file(folder, f)  # read files content
        # (... do some stuff to process data)

    for w in config.NAME_LIST:
        folder = "/data/test/{name}/in".format(name=w)
        files = list_files(folder) # return a list of files found in folder
        [_process(f) for f in files] # using list comprehension 

Are List Comprehension a good solution in this case? Any better way to achieve this?

There are some hacks with filter or any to avoid the unnecessary output ( Is there a map without result in python? ) but the for loop is probably the most idiomatic approach? Is there a reason you want it flat?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM