简体   繁体   中英

Python: How to merge two lists into one

I have a code like this:

if list1:
    merged += list1
    list1 = []
elif list2:
    merged += list2
    list2 = []

So I append one list to another list and then make it empty. Is there any ways to write whis part:

merged += list1
list1 = []

shorter and faster (more efficient), on one line using a function etc?

You can put the assignments on one line:

if list1:
    merged, list1 = merged + list1, []
elif list2:
    merged, list2 = merged + list2, []

You can pick the source list in one line too:

source = list1 or list2 or []
merged, source[:] = merged + source, []

This updates list1 or list2 if either of them had elements through slice assignment.

Demo:

>>> def demo(list1, list2, merged):
...     source = list1 or list2 or []
...     merged, source[:] = merged + source, []
...     return list1, list2, merged
... 
>>> demo([], [], [1, 2])
([], [], [1, 2])
>>> demo([3, 4], [], [1, 2])
([], [], [1, 2, 3, 4])
>>> demo([3, 4], [5, 6], [1, 2])
([], [5, 6], [1, 2, 3, 4])
>>> demo([], [5, 6], [1, 2])
([], [], [1, 2, 5, 6])

That said, I think you should stick to your original version. It is more efficient ( .extend() or += on a list expands the existing list object, the above code always builds an entirely new object, even when list1 and list2 are both empty), and is clear and simple, so more readable. It's great that we get to show off our Python fu from time to time, but this may not be the place, actually. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM