alp*_*uri 2 python list-comprehension
我有一个简单的任务,就是从列表中选择所有元素(按降序排序),它们位于给定元素之上.即
X=[32,28,26,21,14,11,8,6,3]
Threshold=12
Result=[32,28,26,21,14]
Run Code Online (Sandbox Code Playgroud)
我最初做的是简单的事情
FullList=[x for x in FullList if x>=Threshold]
Run Code Online (Sandbox Code Playgroud)
但是,由于列表已经排序,我可以(并且需要)介于两者之间.
多撞头和一个美丽的教程后在这里,我终于想出了以下解决方案.
def stopIteration():
raise StopIteration
FullList=list(x if x>=Threshold else stopIteration() for x in FullList )
Run Code Online (Sandbox Code Playgroud)
但是,当我写下面的语句时,它给我一个语法错误:
FullList=list(x if x>=Threshold else raise StopIteration for x in FullList )
Run Code Online (Sandbox Code Playgroud)
这种行为背后的原因是什么?
raise 是一个语句,但在另一个语句中,您只能使用表达式.
另外,为什么不使用itertools.takewhile?
full_list = list(itertools.takewhile(lambda x: x >= threshold, full_list))
Run Code Online (Sandbox Code Playgroud)