Python appending two returns to two different list

2019-09-16 15:56发布

I am wanting to append two returned lists to two different lists such as

def func():
    return [1, 2, 3], [4, 5, 6]

list1.append(), list2.append() = func()

Any ideas?

3条回答
成全新的幸福
2楼-- · 2019-09-16 16:14

Why not just storing the return values?

a, b = func() #Here we store it in a and b
list1.append(a) #append the first result to a
list2.append(b) #append the second one to b

With this, if a was previously [10] and b was previously [20], you'll have this result:

>>> a, b
[10, [1,2,3]], [20,[4,5,6]]

Nah, that wasn't difficult, was it?

By the way, you probably want to merge the lists. For this, you can use extend:

list1.extend(a)

Hope it helps!

查看更多
萌系小妹纸
3楼-- · 2019-09-16 16:24

You'll have to capture the return values first, then append:

res1, res2 = func()
list1.append(res1)
list2.append(res2)

You appear to be returning lists here, are you certain you don't mean to use list.extend() instead?

If you were extending list1 and list2, you could use slice assignments:

list1[len(list1):], list2[len(list2):] = func()

but this is a) surprising to newcomers and b) rather unreadable in my opinion. I'd still use the separate assignment, then extend calls:

res1, res2 = func()
list1.extend(res1)
list2.extend(res2)
查看更多
家丑人穷心不美
4楼-- · 2019-09-16 16:36

A one line solution isn't possible (unless you use some cryptic hack, which is always a bad idea).

The best you can get is:

>>> list1 = []
>>> list2 = []
>>> def func():
...     return [1, 2, 3], [4, 5, 6]
...
>>> a,b = func()     # Get the return values
>>> list1.append(a)  # Append the first
>>> list2.append(b)  # Append the second
>>> list1
[[1, 2, 3]]
>>> list2
[[4, 5, 6]]
>>>

It's readable and efficient.

查看更多
登录 后发表回答