Omri. B
Omri. B

Reputation: 462

Using list comprehension with over 4 conditions

I have a list of lists. Each sub-list contains two integer elements. I would like to multiply each of these elements by 1.2 and if they are positive and bigger then a certain number, change them to be that certain number. same thing if they are smaller. The multiplication bit I achieved using list comprehension. With these extra conditions, I'm getting a little lost - to me, it seems overly complicated and even non pythonic. I was wondering if I can get some opinions.

The multiplication bit I achieved using list comprehension. With these extra conditions, I'm getting a little lost - to me, it seems overly complicated and even non pythonic. I have a rough idea on how to put all the conditions in the list comprehension, but when I started implementing them I got confused. I was wondering if I can get some opinions.

MAX_VOL = 32767  # audio data is the list of lists
MIN_VOL = -32767
audio_list = [[int(x*1.2), int(y*1.2)] for x, y in audio_data]

# My idea was something like:
audio_list = [[int(x*1.2), int(y*1.2) if x > MAX_VOL x == MAX VOL if x < MIN_VOL....] for x, y in audio_data]

Firstly, I'm pretty sure there is a syntax issue. But, for each number, I have to check if its positive or negative, then, if it is bigger or smaller then max/min volume. So, is this possible using list comprehension? Is it efficient and pythonic?

Thank you so much!

Upvotes: 1

Views: 84

Answers (3)

If a list comprehension is too complex, then don't use it. You should try and make your solution easy for someone else to understand and for you to understand if you come back to it in a year.

for x,y in audio_data:
    if x > MAX_VOL:
        foo = int(x*1.2)
        bar = int(y*1.2)
    if x == MAX_VOL:
        ...

Upvotes: 0

KYDronePilot
KYDronePilot

Reputation: 545

Define a bounding function that doesn't let the value exceed the max or min volume. Then you can still use list comprehension.

MAX_VOL = 32767  # audio data is the list of lists
MIN_VOL = -32767

# Ensure volume does not exceed limits.
def bounded(val):
    if val > MAX_VOL:
        return MAX_VOL
    elif val < MIN_VOL:
        return MIN_VOL
    return val

audio_list = [[bounded(int(x*1.2)), bounded(int(y*1.2))] for x, y in audio_data]

Upvotes: 1

Daniel
Daniel

Reputation: 42758

Use min and max:

MAX_VOL = 32767  # audio data is the list of lists
MIN_VOL = -32767

audio_list = [[int(max(MIN_VOL, min(MAX_VOL, x*1.2))), int(max(MIN_VOL, min(MAX_VOL, y*1.2)))] for x, y in audio_data]

And since these are long expressions, use a function, too:

def clip(s):
    return int(max(MIN_VOL, min(MAX_VOL, s)))
audio_list = [[clip(x*1.2)), clip(y*1.2)] for x, y in audio_data]

Upvotes: 2

Related Questions