If-else if in list comprehension

sodiqolabodeafolayan:

can_ride_coaster = [can_ride_coaster for can_ride_coaster in heights if can_ride_coaster > 161]

The beauty of list comprehensions is that they are abstracts of an otherwise verbose task. Given that, it would follow that we dont need verbosity in them.

@midlindner demonstrates that above by using a simple letter symbol in place of a verbose name.

can_ride_coaster = [x for x in heights if x > 161]

The variable name tells us what is being abstracted. That is sufficient information to permit not infusing the abstraction with all that clutter.

In the end, it helps to get to the bottom of the mechanics in play. Abstractions are generic, like functions. The verbosity needs to left where it has real meaning and not be allowed to pollute otherwise re-usable functions or one-off abstractions.

Witness

def passes[h, d]: return h > d def can_ride[array, disallowed]: return [x for x in array if passes[x, disallowed]] >>> heights = [161, 164, 156, 144, 158, 170, 163, 130, 163, 157] >>> can_ride_coaster = can_ride[heights, 161] >>> can_ride_ferris_wheel = can_ride[heights, 135] >>> can_ride_coaster [164, 170, 163, 163] >>> can_ride_ferris_wheel [161, 164, 156, 144, 158, 170, 163, 163, 157] >>>

Video liên quan

Chủ Đề