【问题标题】:Breaking from a loop in list comprehension in python打破python列表理解中的循环
【发布时间】:2014-09-13 16:52:30
【问题描述】:

我有一个简单的任务,即从列表(按降序排序)中选择位于给定元素上方的所有元素。 即

X=[32,28,26,21,14,11,8,6,3]
Threshold=12
Result=[32,28,26,21,14]

我最初所做的只是一些简单的事情

FullList=[x for x in FullList if x>=Threshold]

但是,由于列表已排序,我可以(并且需要)介于两者之间。

经过大量的头撞和漂亮的教程here,我终于想出了以下解决方案。

 def stopIteration():
      raise StopIteration

 FullList=list(x if x>=Threshold else stopIteration() for x in FullList )

但是,当我编写以下语句时,它给了我一个语法错误:

FullList=list(x if x>=Threshold else raise StopIteration for x in FullList )

这种行为背后的原因是什么?

【问题讨论】:

  • x if x>=Threshold else raise StopIteration 不是有效的表达式,因为raise StopIteration 没有值,因此无法将其添加到列表中。你有什么理由不为此使用循环?
  • 您应该更仔细地阅读您提到的教程。它回答了您的特定问题(不是有效的表达式)并提到使用 itertools.takewhile 以及使用用户定义的函数 stopif() 来在隐式理解循环中引发 StopIteration 的有点骇人听闻的(IMO)方法——这确实是一个漂亮的很好的教程。

标签: python list-comprehension


【解决方案1】:

raise 是一个语句,但在另一个语句中你只能使用表达式。

另外,为什么不使用itertools.takewhile?

full_list = list(itertools.takewhile(lambda x: x >= threshold, full_list))

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 2013-09-10
    • 2017-01-28
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2014-11-18
    相关资源
    最近更新 更多