如何以Python方式从列表中产生所有值? [英] How to Pythonically yield all values from a list?

查看:92
本文介绍了如何以Python方式从列表中产生所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表,我不想返回但要从中产生值.最Python的方式是什么?

Suppose I have a list that I wish not to return but to yield values from. What is the most pythonic way to do that?

这是我的意思.多亏了一些非延迟计算,我才计算出列表['a', 'b', 'c', 'd'],但是我在整个项目中的代码使用了延迟计算,因此我想从函数中产生值,而不是返回整个列表.

Here is what I mean. Thanks to some non-lazy computation I have computed the list ['a', 'b', 'c', 'd'], but my code through the project uses lazy computation, so I'd like to yield values from my function instead of returning the whole list.

我目前将其编写如下:

my_list = ['a', 'b', 'c', 'd']
for item in my_list:
    yield item

但是,这对我来说并不好用.

But this doesn't feel pythonic to me.

推荐答案

使用iter创建列表迭代器,例如

Use iter to create a list iterator e.g.

return iter(List)

尽管如果您已经有一个列表,则可以将其返回,这样会更有效率.

though if you already have a list, you can just return that, which will be more efficient.

这篇关于如何以Python方式从列表中产生所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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