简体   繁体   中英

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.

Also, why not use itertools.takewhile ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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