[英]Find the first N elements of a list, until a condition is satisfied
I have a list of objects, and I want to take the beginning of the list up until the first object that meets a simple condition (like imp[1] == 'conversion'
when imp
is some element in the list). 我有一个对象列表,我想从列表的开头开始,直到第一个满足简单条件的对象为止(当
imp
是列表中的某个元素时,例如imp[1] == 'conversion'
)。
An easy way would be: initialize a new list, iterate through the original list, and at each step append the current element and check the condition on the current element. 一种简单的方法是:初始化一个新列表,遍历原始列表,然后在每个步骤中追加当前元素并检查当前元素的条件。 If the condition is not satisfied then continue, and if it is satisfied then break.
如果不满足条件,则继续,如果满足,则中断。
new_list = []
for ele in old_list:
new_list.append(ele)
if condish(ele):
break
But this seems inefficient in memory, runtime, and code (the big three!). 但是,这似乎在内存,运行时和代码(前三项!)方面效率低下。
You can try this: 您可以尝试以下方法:
for idx, el in enumerate(your_list):
if satisfies_condition(el):
return your_list[:idx]
which will save you the cost of creating a new list in memory. 这样可以节省您在内存中创建新列表的成本。
Or you can use itertools.takewhile
或者您可以使用
itertools.takewhile
return list(itertools.takewhile(not_condition, your_list))
There is itertools.takewhile
which should satisfy your need. 有
itertools.takewhile
应该可以满足您的需求。 Of course, here you need to negate the condition in your original post so that you break when the condition is met... 当然,这里您需要在原始帖子中取消条件,以便在满足条件时中断...
itertools.takewhile(lambda ele: not condish(ele), old_list)
If you want more flexibility and control (eg you also want to take the first element that doesn't meet the condition), it might be worth considering a generator function: 如果您想要更多的灵活性和控制力(例如,您还想采用不满足条件的第一个元素),那么可能值得考虑使用生成器函数:
def take_until(iterable):
for item in iterable
yield item
if condition(item):
return
then you use it like this: 然后您可以像这样使用它:
for item in take_until(old_list):
...
This avoids building a list that you don't really need/want and gives you an iterable instead. 这样可以避免构建您实际上不需要/想要的列表,而为您提供可迭代的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.