Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Multiple for loops in list comprehensions (if that's what's meant by "multi-level") are pretty straightforward once you realise the simple rule that translates them into loops: write everything to the right of the expression in the same order with nesting. For example this:

    l = [f(x, y) for x in X for y in Y if x > y]
is the same as this:

    l = []
    for x in X:
        for y in Y:
             if x > y:
                 l.append(f(x,y))
If a list comprehension doesn't fit on one line I try to highlight this to any future reader by using one line per thing that would get nested:

    l = [
        f(x, y) 
        for x in X 
        for y in Y 
        if x > y
    ]
Needless to say, there are still list comprehensions that are complex enough that they ought to be broken out into loops. But being nested isn't enough by itself.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: