我试图在没有修改输入的情况下移动第一个和第二个字符,但是因为我使用holder
来保持输入似乎被修改了,有人知道另一种不会修改它的方法吗?
shiftlist = ['a', 'b', 'c']
def switch(shiftlist):
holder = shiftlist[0]
shiftlist[0] = shiftlist[1]
shiftlist[1] = holder
return shiftlist
您可以传递列表的副本,而不是列表本身。
print(switch(shiftlist.copy()))
print(shiftlist)
['b', 'a', 'c']
['a', 'b', 'c']
首先,读取列表在赋值后发生意外变化。为什么会出现这种情况?我该如何预防?
这个例子有点不同,因为它是一个函数。传递实参对函数作用域内的形参名进行隐式赋值。
一种选择是传递一个副本(就像Stuart的回答一样),但这意味着输入列表将得到修改后的和返回的,这是非常规的。相反,在函数中复制一个。
def switch(shiftlist):
new = shiftlist.copy()
new[0], new[1] = new[1], new[0] # BTW, no temporary variable needed
return new
L = ['a', 'b', 'c']
print(switch(L)) # -> ['b', 'a', 'c']
print(L) # -> ['a', 'b', 'c']