简体   繁体   中英

Conditional list comprehension without else

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.

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

List comphrensions support the inclusion of a predicate.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM