Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional list comprehension without else

Tags:

python

I have the following solution, however its wasteful to loop over the data again to remove pointless white-space (" ") placed in to satisfy the compiler. I wish to keep this solution compact and in-line as shown.

How could I rewrite this to only return values on one condition?

ans = [x[0] if x[1]==minimum else " " for x in zip(a,b)]
like image 423
Aiden Faulconer Avatar asked Apr 09 '26 20:04

Aiden Faulconer


1 Answers

List comprehensions support the inclusion of a predicate to filter the items.

I think you want:

ans = [x[0] for x in zip(a,b) if x[1]==minimum]

or maybe a little clearer like this:

ans = [x for (x,y) in zip(a,b) if y==minimum]
like image 153
khelwood Avatar answered Apr 11 '26 10:04

khelwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!