Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

python - Why can't I assign an arbitrary iterable to an extended slice whose step is -1?

Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> u = [4, 5, 6, 7, 8, 9]
>>> u[1::1] = [3, 2, 1, 0]
>>> u
[4, 3, 2, 1, 0]
>>> u[9:0:-1] = [8, 7, 6, 5]
>>> u
[4, 5, 6, 7, 8]
>>> u[9:0:-1] = [16, 12, 8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 3 to extended slice of size 4
>>> u
[4, 5, 6, 7, 8]
>>>

Expected behaviour: no exception thrown on final assignment statement; u should print on final line as [4, 8, 12, 16].

I can assign to an extended slice whose step is 1, even if the iterable I'm assigning is "the wrong length". Why then can't I assign to an extended slice whose step is -1 and have it work in the obvious way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think that creating an extended slice whose step is 1 effectively acts like a regular slice rather than an extended slice.

Extended slices do not allow you to change the length of the sequence, as noted here

If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, but there are some differences between assignment to extended and regular slices. Assignment to a regular slice can be used to change the length of the sequence. Extended slices aren't this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing.

As for why it's works this way, I can only guess it is because of the cases where there is no obvious behaviour. Take this example:

u = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
u[0:8:3] = [ 10, 11 ]

How would you expect this to work? I guess you could just replace 1 & 4 with 10 & 11, but what about 7? Do you leave it? Delete it? Delete the entire rest of the sequence past 7? Maybe it's just me, but this case doesn't seem too clear cut. Which I would assume is why this sort of behaviour just wasn't allowed for extended slices.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...