Swap indexes using slices?

2019-07-14 04:50发布

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:

3条回答
姐就是有狂的资本
2楼-- · 2019-07-14 05:23

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
查看更多
戒情不戒烟
3楼-- · 2019-07-14 05:39

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'.

查看更多
姐就是有狂的资本
4楼-- · 2019-07-14 05:45
>>> 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']
查看更多
登录 后发表回答