开发者

Python: Add item to list until a condition is true

Normal list compreh开发者_运维知识库ensions occur this way:

new_list = [f(x) for x in l]

What is the most succinct and readable way to create new list in Python similar to this:

new_list = [f(x) while condition is True]


Keep it simple:

new_list = []
while condition:
    new_list.append(f(x))

There is no benefit to forcing something into a single expression when it is more clearly written as separate statements.


Use itertools:

import itertools as it

new_list = map(f, it.takewhile(condition, l))

it is the same like

new_list = [f(x) for x in it.takewhile(lambda x: condition(x), l)]


I would probably wrap it in a generator-function:

def generate_items():
    while condition:
        yield f(x)
new_list = list(generate_items)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜