简体   繁体   English

有条件的列表理解

[英]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. 我希望保持该解决方案的紧凑和内联,如图所示。

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)]

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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