简体   繁体   中英

Moving multiple items from one list to another in single line in Python

I'd like to move multiple items from one list to another.
The items are to be removed from the first list and inserted at the end of the second list.
The value of the items are unknown but the indexes of the items are known.
I'd like to do so in one line of code.
The code below does what I'd like but not in one line of code:

listOne = [0, 1, 2, 3, 4, 5]
listTwo = [6, 7, 8, 9, 10]

listTwo = listTwo +listOne[0:2]
listOne = listOne[2:]

Is there a clean way to do so using functions (such as pop(), inser() etc.) in conjunction with each other?

You can make something like that

listOne = [0, 1, 2, 3, 4, 5]
listTwo = [6, 7, 8, 9, 10]

# Must respect this criteria : 0 <= X < Y <= len(listOne)
Y = 2
X = 0

listTwo.extend([listOne.pop(X) for _ in range(Y-X)])
print(listTwo) # [6, 7, 8, 9, 10, 0, 1]
print(listOne) # [2, 3, 4, 5]

Correction based on the jarmod comment

You can put your solution itself on one line -

listOne = [0, 1, 2, 3, 4, 5]
listTwo = [6, 7, 8, 9, 10]
listTwo, listOne = listTwo +listOne[0:2], listOne[2:]

print(listTwo)
# [6, 7, 8, 9, 10, 0, 1]
print(listOne)
# [2, 3, 4, 5]

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