Home > Net >  (Oneliner) append returned list into different lists
(Oneliner) append returned list into different lists

Time:09-16

im looking for a oneliner (if possible) to return three values of a function and append them to three different lists directly after (here a, b, c).

My printout is "1 3 9" right now as my variables get repurposed in the loop. Im looking for following printout: [1, 1, 1] [3, 3, 3] [9, 9, 9]

Do you have an idea? Otherwise im going for a three- or four-liner. Id like to challenge pythons semantic though. ;)

def return_values_list():
"""Simple function to test how returns work."""
    return [1, 3, 9]

a, b, c = [], [], []

for n in range(3):
    a, b, c = return_values_list()

print (a, b, c)

CodePudding user response:

You probably need to work with zip, e.g.,

>>> list(zip(*(return_values_list() for _ in range(3))))
[(1, 1, 1), (3, 3, 3), (9, 9, 9)]

or, if you want to assign to a, b, c,

>>> a, b, c = zip(*(return_values_list() for _ in range(3)))
>>> a
(1, 1, 1)
>>> b
(3, 3, 3)
>>> c
(9, 9, 9)

which is of course equivalent to

>>> from itertools import repeat
>>> a, b, c = zip(*repeat(return_values_list(), 3))

but it wasn't clear if imports are allowed.

CodePudding user response:

You can try this

a=[1,2,3] c=np.repeat(a,3)

CodePudding user response:

Using the zip function along with a list comprehension can achieve this:

def return_values_list():
    """Simple function to test how returns work."""
    return [1, 3, 9]

a, b, c = [], [], []

for n in range(3):
    [data.append(value) for data, value in zip([a, b, c], return_values_list())]

print (a, b, c)

To even make the loop part of the one-liner:

def return_values_list():
    """Simple function to test how returns work."""
    return [1, 3, 9]

a, b, c = [], [], []

[data.append(value) for data, value in zip([a, b, c], return_values_list()) for _ in range(3)]

print (a, b, c)

CodePudding user response:

Another possible solution:

a, b, c = np.split(np.repeat(return_values_list(), 3), 3)

Output:

(array([1, 1, 1]), array([3, 3, 3]), array([9, 9, 9]))

CodePudding user response:

You could construct a list of lists then unpack them into your variables

a, b, c = [[e]*3 for e in (1, 3, 9)]

print(a, b, c)

Output:

[1, 1, 1] [3, 3, 3] [9, 9, 9]
  • Related