Python:操作列表
问题描述:
作为编程的初学者,我试图用Python来做到这一点。我想要一个简单的函数,它将一个列表作为参数,并返回另一个列表,它仅仅是原始列表旋转一次(因此rotate([1, 2, 3])
将返回[2, 3, 1]
),同时保持原始列表不变。Python:操作列表
我知道,这一个
def rotate(list):
list.append(list[0])
list.remove(list[0])
将改变地方列表(和返回无)。
但是这一次
def rotate_2(list):
temp = list
temp.append(temp[0])
temp.remove(temp[0])
return temp
也会改变,以代替原始表(在返回所需的列表)。
,第三个
def rotate_3(list):
temp = [x for x in list]
temp.append(temp[0])
temp.remove(temp[0])
return temp
得到所需的结果,一方面保持原来不变的是返回一个新的列表。我不能理解rotate_2
的行为。为什么当list
函数只是在temp
上执行某些操作时会被更改?它给了我一种感觉,就好像list
和temp
被temp = list
“连接”了。为什么rotate_3
没问题?对不起,如果我的英文很奇怪,那不是我的第一语言(不像Python)。
答
在rotate_2
,temp
和list
指的是相同的列表,所以当你改变一个,他们都改变。
在rotate_3
中,您正在复印。使复印件稍微更习惯的方法是:
temp = list[:]
如下我个人会写这样的功能:
def rotate_4(l):
return l[1:] + [l[0]]
这使用slicing和list concatenation。
请注意,我已将list
更名为l
,因为list
是built-in name。
因为'temp = list **不**创建副本,不像'rotate_3'中的列表理解。 – jonrsharpe 2014-10-05 20:52:26