Assign to a slice of a Python list from a lambda
I know that there are certain "special" methods of various objects that represent operations that would normally be performed with operators (i.e. int.__add__
for +, object.__eq__
for ==, etc.), and that one of them is 开发者_Python百科list.__setitem
, which can assign a value to a list element. However, I need a function that can assign a list into a slice of another list.
Basically, I'm looking for the expression equivalent of some_list[2:4] = [2, 3]
.
The line
some_list[2:4] = [2, 3]
will also call list.__setitem__()
. Instead of an index, it will pass a slice
object though. The line is equivalent to
some_list.__setitem__(slice(2, 4), [2, 3])
It depends on the version of Python. For 3.2, __setitem__
does the job:
Note Slicing is done exclusively with the following three methods. A call like a[1:2] = b is translated to a[slice(1, 2, None)] = b and so forth. Missing slice items are always filled in with None.
精彩评论