星海's Blog

老头初学编程
Python相关的网站

关于L[3:1]=['x']=L.insert(3,'x')的解答

星海 posted @ 2010年10月05日 08:12 in Python杂谈 , 1519 阅读

Python scales the slice limits to make sure that the lower bound is always less than
or equal to the upper bound (e.g., L[3:1] is scaled to L[3:3], the empty insertion
point at offset 3). Python slices are always extracted from left to right, even if you
use negative indexes (they are first converted to positive indexes by adding the
sequence length)

 

在comp.lang.python新闻组有人回复了这个问题


To specify a backwards slice, you have to supply the third slice argument:

L[3:1:-1]

As it stands, `L[3:1]=['?']` replaces the empty sequence at index 3 with the
contents of ['?'].  You know that `L[3:1]` is empty from the display above
the print statement.

The language manual has slicing defined as "a[i:j] selects all items with
ndex k such that i <= k < j".  This is true as far as it goes but the
tutorial is truly on to something when it says "see where the value is put."

Python won't build a sequence that's less-than-empty, so it deals with an
empty sequence here.  We're probably due for an argument on whether it
should raise an exception instead.  See the current thread on whether `+`
should be a sequence concatenation operator.

        Mel.

 

L1[a:b] = L2 removes all elements in L1 between a and b and inserts L2
at the start index. If 0 <= a < b then that removes no elements and
inserts the new ones. Seems like the most sensible and consistent
behaviour to me.

Chard.

 

顺便感叹下新闻组热心人真多啊 -__-


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter