且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从python中的for循环返回值

更新时间:2023-02-03 11:18:43

[bean for bean in beans if bean.type == 'coffee']

列表理解整洁.即使更加整洁,通常也不需要生成整个列表-您只需要一个迭代器即可为您提供列表将包含的值.那是一个生成器,它们可以通过生成器表达式简洁地表示.它们的编写方式与列表理解方式相同,除了方括号变成括号(并且,如果它是函数调用中的唯一参数,则可以忽略它们),例如'\n'.join(str(bean) for bean in beans if bean.type == 'coffee').优点是提到的懒惰,即您在真正需要(要求)它们之前就不会生成值,并且您不会同时将所有值都保留在内存中(除非消费者这样做).

List comprehensions are neat. Even neater, often you don't need to produce a whole list - you just need an iterator that gives you the values the list would consist of. That's a generator, and they can be expressed just as succinctly via generator expressions. Those are written in the same way as list comprehensions except that the square brackets become parens (and you can omit them if it's the only argument in a function call) e.g. '\n'.join(str(bean) for bean in beans if bean.type == 'coffee'). The advantage is the mentioned laziness, i.e. you never generate values until they're really needed (requested) and you don't keep all of them in memory at the same time (unless of course the consumer does this).

您可以使用itertools.chain将多个可迭代对象(包括列表)链接到一个,或者,如果您无法更改获取列表列表的事实,则可以使用(x for list in lists for x in list).对于涉及自动深层嵌套的通用解决方案,您需要使用递归的完整功能.

You can use itertools.chain to chain multiple iterables (including lists) to one, or if you can't change the fact you're getting lists of lists, you can use (x for list in lists for x in list). For a generalized solution involving abritary deep nesting, you need a full function utilizing recursion.