使用切片交换索引? [英] Swap indexes using slices?
问题描述
我知道你可以在Python中交换2个单个索引
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]
输出:
['1', '2', '5', '4', '3', '6', '7', '8']
但是为什么你不能在python中交换2片索引?
But why can't you swap 2 slices of indexes in python?
r = ['1', '2', '3', '4', '5', '6', '7', '8']
我想将数字3 + 4与5 + 6 + 7换成r:
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]
输出:
['1', '2', '5', '6', '3', '4', '7', '8']
预期产出:
['1', '2', '5', '6', '7', '3', '4', '8']
我错了什么?
输出:
What did I wrong? output:
推荐答案
切片工作正常。您正在更换不同长度的切片。 r [2:4]
是两项, r [4:7]
是三项。
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']
所以当 ['3','4']
被替换时,它只能适合 ['5','6']
,当 ['5','6','7']
被替换时,它只获得 ['3' ,'4']
。所以你有 ['1','2',
,然后接下来的两个元素是 ['5','6中的前两个元素','7']
这只是 ['5','6'
,然后来自的两个元素[ '3','4'
接下来,然后剩下的'7','8']
。
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
这篇关于使用切片交换索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!