从列表中返回每个元素(Python) [英] Returning every element from a list (Python)

查看:105
本文介绍了从列表中返回每个元素(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个函数可以在 Python 中返回多个值.我想做的是将列表中的每个元素作为单独的返回值返回.这可以是任意数量的元素,具体取决于用户输入.我想知道是否有这样做的pythonic方式?

I know that it is possible for a function to return multiple values in Python. What I would like to do is return each element in a list as a separate return value. This could be an arbitrary number of elements, depending on user input. I am wondering if there is a pythonic way of doing so?

例如,我有一个函数将一对项目作为数组返回,例如,它将返回 [a, b].

For example, I have a function that will return a pair of items as an array, e.g., it will return [a, b].

但是,根据给定的输入,函数可能会产生多对,这将导致函数返回[[a, b], [c, d], [e, f]].相反,我希望它返回 [a, b], [c, d], [e, f]

However, depending on the input given, the function may produce multiple pairs, which will result in the function returning [[a, b], [c, d], [e, f]]. Instead, I would like it to return [a, b], [c, d], [e, f]

截至目前,我已经实现了一个非常粗制滥造的函数,其中包含大量临时变量和计数,正在寻找更清晰的建议.

As of now, I have implemented a very shoddy function with lots of temporary variables and counts, and am looking for a cleaner suggestion.

感谢您的帮助!

推荐答案

有一个yield 语句与此用例完美匹配.

There is a yield statement which matches perfectly for this usecase.

def foo(a):
    for b in a:
        yield b

这将返回一个可以迭代的生成器.

This will return a generator which you can iterate.

print [b for b in foo([[a, b], [c, d], [e, f]])

这篇关于从列表中返回每个元素(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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