python - 打破python中列表理解的循环

标签 python list-comprehension

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

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 )

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

最佳答案

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

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

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

关于python - 打破python中列表理解的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25821466/

相关文章:

python:循环的单线笛卡尔积

python - 创建没有特定范围的数组

python - 根据条件用真实值填充数据框

python - Seaborn 和 Pandas,分组箱线图

python - 为什么我得到 valueerror?

F# 中的 Haskell 列表推导式守卫

python - Matplotlib-动画 "No MovieWriters Available"

python - 无法返回从文件(.csv)读取的列表

python - 对元组列表中的每个值求和

python - 使用列表理解生成字典列表的问题