从python中的for循环返回值 [英] Returns values from a for loop in python

查看:1970
本文介绍了从python中的for循环返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出在for循环语法中将参数从一个列表或dict传递到另一个列表或dict的语法.

I'm trying to figure out the syntax for passing arguments from one list or dict to another in the for loop syntax.

我正在寻找的理想结果是这样:

The desired result I'm looking for is this:

 for bean in beans:
  if bean.type == 'coffee':
   print bean

我只想收集该字符串数据并将其附加到另一个列表,而不是打印到stdout.最终使列表变平.

Only, instead of printing to stdout, I'd like to collect that string data and append it to another list. Eventually flattening the list.

踢球者,我想在一行中执行此操作.

The kicker, I want to perform this in a single line.

我知道''.join()方法,我在寻找这个结果,以便可以从for-in循环中过滤结果.

I know of the ''.join() method, I'm looking for this result so I can filter the results from the for-in loop.

推荐答案

[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.

这篇关于从python中的for循环返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆