Swap indexes using slices?

百般思念 提交于 2019-12-11 01:17:19

问题


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


来源:https://stackoverflow.com/questions/36952565/swap-indexes-using-slices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!