user7864386
user7864386

Reputation:

List comprehension with multiple if-conditions

I want to write the following bit of code in a pythonic way but having trouble at the moment:

X = [1, 2, 3, 4, 5, 6, 7]
Y = [1, 4, 6, 2]


aa = []
max_a = []
for x in X:
    for y in Y:
        a = x*y
        if a > 8 :
            aa.append(a)
    if aa != []:
        max_a.append(max(aa))
    aa = []
np.mean(max_a)

I got to:

np.mean([max(x*y for y in Y if x*y>8) for x in X])

but it's giving me ValueError: max() arg is an empty sequence because for X[0], aa = []. Essentially, there needs to be check for an empty list before doing the max, there but I don't know how to include that. Any help is appreciated.

Upvotes: 0

Views: 77

Answers (2)

Jan Matejka
Jan Matejka

Reputation: 1970

xs = [[x*y for y in Y if x*y > 8] for x in X]
xs = [max(x) for x in xs if x]
np.mean(xs)

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

What you are specifically asking can be done like this:

>>> np.mean([max(x*y for y in Y if x*y>8) for x in X if any(x*y for y in Y if x*y>8)])
27.0

But it's quite long, rather:

>>> np.nanmean([max([x*y for y in Y if x*y>8], default=np.nan) for x in X])
27.0

However, both are ugly. Following would be cleaner:

>>> mul = np.multiply(np.array(X)[:,None], Y).max(1)
>>> np.mean(mul[mul > 8])
27.0

Upvotes: 1

Related Questions