简体   繁体   中英

Convert function to single line list comprehension

Is it possible to convert this function, list comprehension combination into a single list comprehension (so that keep is not needed)?

def keep(list, i, big):
    for small in list[i+1:]:
        if 0 == big % small:
            return False
    return True

multiples[:] = [n for i,n in enumerate(multiples) if keep(multiples, i, n)]

I think this is it:

multiples[:] = [n for i,n in enumerate(multiples) 
                       if all(n % small for small in multiples[i+1:])] 

multiples[:] = [n for i, n in enumerate(multiples) if 0 not in [n % other for other in multiples[i+1:]]

Advisible? Probably not.

First thing is to learn to not use names like list in your code. Remember also the "first make it work, then optimize". If you continue to learn things, it is likely that in any case after one month you are not any more happy with your code. Try to make readable code. For that it helps if you can (heaven forbid!) read your own code after putting it aside for few weeks.

That said, it is actually more readable sometimes to make list comprehension, but often you can do it only after writing more stupid version of code.

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