Python appending two returns to two different lists

老子叫甜甜 提交于 2019-12-13 04:39:38

问题


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?


回答1:


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)



回答2:


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:


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.



来源:https://stackoverflow.com/questions/19879587/python-appending-two-returns-to-two-different-lists

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