【发布时间】:2013-11-06 05:08:30
【问题描述】:
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 这个函数所做的是将我们输入的索引的数字与后面的数字交换。
应该是这样的
>>> x = [1,2,3,4,5]
>>> swap_numbers(x,2)
>>> x
[1,2,4,3,5]
但我的是
>>> 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]]
我该怎么办?
【问题讨论】:
-
num和num_list是什么?那些应该是x和x_index? -
呃...opps,谢谢你告诉我,已经切换了:P
-
你为什么使用循环
for num in x:? -
@njzk2 哈哈,没关系,我以为我需要它,我是 python 的初学者,所以....哈哈,这是一个愚蠢的错误
-
你原来的 cdde 会工作,我想,如果你只是删除
for行......