开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜