def swap_numbers(x, x_index):
for num in x:
if x_index < len(x)-1:
x[:] = x[:x_index] + [x[x_index+1]] + [x[x_index]]+ x[x_index+2:]
elif x_index == len(x)-1:
x[:] = [x[-1]] + x[1:-1] + [x[0]]
所以如果我想改变一个列表,让x=[1,2,3,4,5]和x_index=2 这个函数的作用是用下面的数字交换我们输入的索引的编号。在
应该是这样的
^{pr2}$但我的是
>>> x = [1,2,3,4,5]
>>> swap_numbers(x,2)
>>> x
[1,2,3,4,5]
不过,如果我把函数的第一部分
x[:] = [x[:x_index] + [x[x_index+1]] + [x[x_index]] + x[x_index+2:]]"
它就会变成
>>> x = [1,2,3,4,5]
>>> swap_numbers(x,2)
>>> x
[[1,2,4,3,5]]
我该怎么办?在
也许是这样的:
这就产生了:
^{pr2}$这取决于您希望如何处理索引错误(交换不存在),但这是可行的:
这不会做任何不能做的事情,比如
swap_numbers(x,5)
相关问题 更多 >
编程相关推荐