可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I know that you can swap 2 single indexes in Python
r = ['1', '2', '3', '4', '5', '6', '7', '8']
r[2], r[4] = r[4], r[2]
output:
['1', '2', '5', '4', '3', '6', '7', '8']
But why can't you swap 2 slices of indexes in python?
r = ['1', '2', '3', '4', '5', '6', '7', '8']
I want to swap the numbers 3 + 4 with 5 + 6 + 7 in r:
r[2:4], r[4:7] = r[4:7], r[2:4]
output:
['1', '2', '5', '6', '3', '4', '7', '8']
expected output:
['1', '2', '5', '6', '7', '3', '4', '8']
What did I wrong?
output:
回答1:
The slicing is working as it should. You are replacing slices of different lengths. r[2:4]
is two items, and r[4:7]
is three items.
>>> r = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> r[2:4]
['3', '4']
>>> r[4:7]
['5', '6', '7']
So when ['3', '4']
is replaced, it can only fit ['5', '6']
, and when ['5', '6', '7']
is replaced, it only gets ['3', '4']
. So you have ['1', '2',
, then the next two elements are the first two elements from ['5', '6', '7']
which is just ['5', '6'
, then the two elements from ['3', '4'
go next, then the remaining '7', '8']
.
If you want to replace the slices, you have to start slices at the right places and allocate an appropriate size in the array for each slice:
>>> r = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> r[2:5], r[5:7] = r[4:7], r[2:4]
>>> r
['1', '2', '5', '6', '7', '3', '4', '8']
old index: 4 5 6 2 3
new index: 2 3 4 5 6
回答2:
Think of this:
r[2:4], r[4:7] = r[4:7], r[2:4]
as similar to this:
original_r = list(r)
r[2:4] = original_r[4:7]
r[4:7] = original_r[2:4]
So, by the time it gets to the third line of that, the 4th element isn't what you think it is anymore... You replaced '3', '4'
with '5', '6', '7'
, and now the [4:7]
slice starts with that '7'
.
回答3:
>>> r = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> r[2:5], r[5:7] = r[4:7], r[2:4]
>>> r
['1', '2', '5', '6', '7', '3', '4', '8']
In your code:
>>> r[2:4], r[4:7] = r[4:7], r[2:4]
You are assigning r[4:7]
which have 3 elements to r[2:4]
which have only 2.
In the code I posted:
>>> >>> r[2:5], r[5:7] = r[4:7], r[2:4]
r[4:7]
which is ['5', '6', '7']
, replaces
r[2:5]
which is ['3', '4', '5']
r
resulting in ['1', '2', '5', '6', '7', '6', '7', '8']
and then:
r[2:4]
which was ['3', '4']
, replaces
r[5:7]
which is ['6', '7']
So final result being:
['1', '2', '5', '6', '7', '3', '4', '8']