[Tutor] While until the end of a list

Peter Otten __peter__ at web.de
Mon Mar 13 14:57:38 EDT 2017


Toni Fuente via Tutor wrote:

> Hi,
> 
> I've got this script that goes through an httpd conf file, and gets the
> related bits of it for a site, and writes a new config with values that
> I am interested. The problem is that it finds the first chunk and
> returns it, but I need to go to the end of all chunks list, because
> there are also some chunks related to the same site that I need to
> collect (virtualhost *:80 and virtualhost:443). I was
> 
> I was thinking in a while loop in the find_chunk function that will go
> through all chunks and return the chunks that site is on, but I don't know
> how to construct it.
> 
> Thank you in advance for any suggestion.

Currently the structure of your script seems to be

chunks = load_chunks()
for site in get_sites():
    interesting_chunk = find_chunk(site, chunks)
    if interesting_chunk is not None:
        do_stuff_with(interesting_chunk)

If I am understanding you correctly you want

chunks = load_chunks()
for site in get_sites():
    for interesting_chunk in find_chunks(site, chunks):
        do_stuff_with(interesting_chunk)


One way to make that work was already mentioned, have find_chunks return a 
list:

def find_chunks(site, chunks):
    matches = []
    for chunk in chunks:
        if any(site in line for line in chunk):
            matches.append(chunk)
    return matches

Another is to use a generator:

def find_chunks(site, chunks):
    for chunk in chunks:
        if any(site in line for line in chunk):
            yield chunk





More information about the Tutor mailing list