Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce multiple list comprehesion into a single statement

Looking for a reduced list comprehesion and less loops and memory usage, there is some way to reduce two loops to build the final paths, transforming it into a single list comprehesion?

def build_paths(domains):

    http_paths  = ["http://%s"   % d for d in domains]
    https_paths = ["https://%s" % d for d in domains] 

    paths = []                                         
    paths.extend(http_paths)                           
    paths.extend(https_paths)

    return paths                          

In this case, the expected result is a optimized list comprehesion, reducing from three list references (http_paths, https_paths, paths) into a single one line, like the following example structure:

def build_paths(domains):
    return [<reduced list comprehesion> for d in domains]

In both cases, running the following test:

domains = ["www.ippssus.com",                      
           "www.example.com",                      
           "www.mararao.com"]                      

print(build_paths(domains))

Expected output, independent of the list order:

< ['http://www.ippssus.com', 'http://www.example.com', 'http://www.tetsest.com', 'https://www.ippssus.com', 'https://www.example.com', 'https://www.tetsest.com']
like image 501
Andre Pastore Avatar asked Dec 08 '22 01:12

Andre Pastore


1 Answers

Add a second loop:

['%s://%s' % (scheme, domain) for scheme in ('http', 'https') for domain in domains]

This builds all the http urls first, then the https urls, just like your original code.

like image 122
Martijn Pieters Avatar answered Dec 15 '22 00:12

Martijn Pieters