[英]Breaking from a loop in list comprehension in python
I have a simple task of selecting all elements from a list (sorted in descending order) that lie above a given element. 我有一个简单的任务,即从给定元素上方的列表(按降序排列)中选择所有元素。 ie
即
X=[32,28,26,21,14,11,8,6,3]
Threshold=12
Result=[32,28,26,21,14]
What I did initially was something simple like 我最初做的事情很简单
FullList=[x for x in FullList if x>=Threshold]
However, since the list is sorted, I can (and need to) break in between. 但是,由于列表已排序,因此我可以(并且需要)在两者之间进行切换。
After much head banging and a beautiful tutorial here , I finally came up with the following solution. 多撞头和一个美丽的教程后在这里 ,我终于想出了以下解决方案。
def stopIteration():
raise StopIteration
FullList=list(x if x>=Threshold else stopIteration() for x in FullList )
However, when I write the following statement, it gives me a syntax error: 但是,当我编写以下语句时,它给了我一个语法错误:
FullList=list(x if x>=Threshold else raise StopIteration for x in FullList )
What is the reason behind this behaviour? 这种行为背后的原因是什么?
raise
is a statement, but inside another statement you can only use expressions. raise
是一个语句,但是在另一个语句中,您只能使用表达式。
Also, why not use itertools.takewhile
? 另外,为什么不使用
itertools.takewhile
呢?
full_list = list(itertools.takewhile(lambda x: x >= threshold, full_list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.