作为一个编程初学者,我尝试用 Python 来做这做那。我想要一个简单的函数,它接受一个列表作为其参数,并返回另一个列表,该列表只是原始列表旋转一次(因此rotate([1, 2, 3])将返回[2, 3, 1]),同时保持原始列表不变。
我知道这个
def rotate(list):
list.append(list[0])
list.remove(list[0])
Run Code Online (Sandbox Code Playgroud)
会就地更改列表(并返回 None)。
但这个
def rotate_2(list):
temp = list
temp.append(temp[0])
temp.remove(temp[0])
return temp
Run Code Online (Sandbox Code Playgroud)
还将更改原始列表(同时返回所需的列表)。
还有第三个
def rotate_3(list):
temp = [x for x in list]
temp.append(temp[0])
temp.remove(temp[0])
return temp
Run Code Online (Sandbox Code Playgroud)
给出了所需的结果,即返回一个新列表,同时保持原始列表不变。
我无法理解 的行为rotate_2。list当函数只是在做某事时为什么会改变temp?它给我一种感觉,好像list是temp被“联系”在一起的temp = list。还有为什么rotate_3可以?抱歉,如果我的英语很奇怪,它不是我的母语(与 Python 不同)。
python ×1