Slater Victoroff
Slater Victoroff

Reputation: 21914

Concatenating list results from multiple functions

So, basically I've got a few functions that return tuples. Essentially of the form:

def function():
    return (thing, other_thing)

I want to be able to add several of these functions together in a straightforward way, like this:

def use_results(*args):
    """
    Each arg is a function like the one above
    """
    results = [test() for test in args]
    things = magic_function(results)
    other_things = magic_function(results)

Basically I have the data structure:

[([item_1, item_1], [item_2, item_2]), ([item_3, item_3], [item_4, item_4])]

and I want to turn it into:

[[item_1, item_1, item_3, item_3], [item_2, item_2, item_4, item_4]]

It seems like there's probably a nice pythonic way of doing this with a combination of zip and *, but it's not quite coming to me.

Upvotes: 0

Views: 49

Answers (2)

Iron Fist
Iron Fist

Reputation: 10951

Without importing any module, just built-in methods:

>>> results = [([1,1], [2,2]), ([3,3], [4,4])]
>>> [x+y for x,y in zip(*results)]
[[1, 1, 3, 3], [2, 2, 4, 4]]

Or even this way as well:

>>> map(lambda s,t:s+t, *results)

Upvotes: 2

Slater Victoroff
Slater Victoroff

Reputation: 21914

Oh, I feel kind of silly. I found an answer quickly after posting the question. I'm going to still keep this up in case there's a better solution though:

>>> import operator
>>> results = [([1,1], [2,2]), ([3,3], [4,4])]
>>> map(operator.add, *results)
[[1, 1, 3, 3], [2, 2, 4, 4]]

Upvotes: 3

Related Questions