Returning every element from a list (Python)

我怕爱的太早我们不能终老 提交于 2019-12-05 10:08:15

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]])

When a python function executes:

return a, b, c

what it actually returns is the tuple (a, b, c), and tuples are unpacked on assignment, so you can say:

x, y, z = f()

and all is well. So if you have a list

mylist = [4, "g", [1, 7], 9]

Your function can simply:

return tuple(mylist)

and behave like you expect:

num1, str1, lst1, num2 = f()

will do the assignments as you expect.

If what you really want is for a function to return an indeterminate number of things as a sequence that you can iterate over, then you'll want to make it a generator using yield, but that's a different ball of wax.

matthewatabet

Check out this question: How to return multiple values from *args?

The important idea is return values, as long as they're a container, can be expanded into individual variables.

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]

Can you not just use the returned list (i.e. the list [[a, b], [c, d], [e, f]]) and extract the elements from it? Seems to meet your criteria of arbitrary number of / multiple values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!