What is the pythonic way of extracting (& removing) a slice from a list? Or... What is the "inverse" of the slice+=list operator - python

StackOverflow https://stackoverflow.com/questions/22343040

Pregunta

I know how insert a list into a list, "slice+=list" ...

master=[0,1,2,3,7,8,9]
master[:4]+=[4,5,6] # insert 4,5,6

(crudely) The inverse of this operation is removing a slice 4:7 from the list, I tried:

extracted=del master[4:7]

But this gives a syntax error "SyntaxError: invalid syntax". Likewise the inverse slice operator "-=" doesn't appear to exist.

As a workaround I have used the following:

extracted=master[4:7]; del master[4:7]

This "works" and the "extracted" is the subslice removed from "master", e.g.

print dict(master=master,extracted=extracted)

Output:

{'extracted': [4, 5, 6], 'master': [0, 1, 2, 3, 7, 8, 9]}

Is there a better/pythonic/simpler way ?

In particular I don't like the repeated [4:7] in:

extracted=master[4:7]; del master[4:7]" 

Because of potential side-effects: eg

extracted=master[randint(0,3):randint(7,10)]; del master[randint(0,3):randint(7,10)]

i.e. the following reads much better, and would have no "side-effects"...

extracted=del master[randint(0,3):randint(7,10)] 

Any hints? Is there a slice "-=" operator I could have used to invert the action of the slice "+=" operator?

¿Fue útil?

Solución

Your best bet is to use a slice:

-> s = slice(4, 7)
-> master
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

--> extracted = master[s]
--> extracted
[4, 5, 6]

--> del master[s]
--> master
[0, 1, 2, 3, 7, 8, 9]

It still requires two commands, but you can use a single object to respresent the piece you want.

Otros consejos

For me the cleaner option is as follows:

>>> L=[1,2,3,4,5,6]  #Define the list
>>> L                #Check it         
[1, 2, 3, 4, 5, 6]
>>> extract= L[3:6] ; L[3:6]=[]   #Assign the slice to 'extract'; delete the slice
>>> L                #Items removed from the list 
[1, 2, 3]
>>> extract          #And assigned to extract
[4, 5, 6]

Cheers!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top