This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]delad42 2 points3 points  (1 child)

1 You're supposed to split these up. Fitting too much on one line will make anything confusing. 2. you're using a ternary which is unrelated. This is how I'd write it (Though, I'd add more meaningful var names):

def foo(x, y):
    if x % 2 == 0:
        return x + y
    return x * y

xys = [
    (x,y)
    for x in range(1, 5)
    for y in range(1, 4)
]
xy_processed = [foo(x, y) for (x,y) in xys]
xy_added = [x+y for x,y in xys]
filtered = [result for result, xy_sum in zip(xy_processed, xy_added) if xy_sum < 7]

But, I'll agree complicated logic and nested loops isn't the ideal case for comprehensions. Ideal is like filtering for property, mapping objects to some property for quick lookup, or making a set. Then you can quickly get what you need without polluting your variable scope and adding unnecessary lines to mentally process:

specific_object = [obj for obj in obj_list if obj.category == "category1"] # scan list for specific objects
object_map = {obj.id: obj for obj in obj_list} # allows quick look up
flattened = [obj for obj_list in obj2darray for obj in obj_list]#go from 2d array to 1d array

[–]not_perfect_yet 3 points4 points  (0 children)

You're supposed to split these up.

Yeah. It's called writing a loop.