使用列表理解中的中断 [英] Using break in a list comprehension

查看:52
本文介绍了使用列表理解中的中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当找到数字 412 时,如何根据条件中断列表理解?

How can I break a list comprehension based on a condition, for instance when the number 412 is found?

代码:

numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
           615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,
           386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399,
           162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67,
           104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842,
           451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527]

even = [n for n in numbers if 0 == n % 2]

从功能上讲,您可以推断应该这样做:

So functionally, it would be something you can infer this is supposed to do:

even = [n for n in numbers if 0 == n % 2 and break if n == 412]

真的更喜欢:

  • 单线
  • 没有其他奇特的库,例如itertools,如果可能,请使用纯python"(阅读:解决方案不应使用任何 import 语句或类似语句)
  • a one-liner
  • no other fancy libraries like itertools, "pure python" if possible (read: the solution should not use any import statement or similar)

推荐答案

even = [n for n in numbers[:None if 412 not in numbers else numbers.index(412)] if not n % 2] 

只需在上面使用F.J.的代码,并添加一个三元代码来检查412是否在列表中.仍然是一个班轮",即使列表中没有412也可以.

Just took F.J.'s code above and added a ternary to check if 412 is in the list. Still a 'one liner' and will work even if 412 is not in the list.

这篇关于使用列表理解中的中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆