【问题标题】:Python: manipulating list in place [duplicate]Python:就地操作列表[重复]
【发布时间】:2014-11-30 04:08:15
【问题描述】:

作为编程的初学者,我试图用 Python 做这个和那个。我想要一个简单的函数,它接受一个列表作为它的参数,并返回另一个列表,它只是原始列表旋转一次(所以 rotate([1, 2, 3]) 将返回 [2, 3, 1] ),同时保持原始列表不变。

我知道这个

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 的行为。当函数只是在 temp 上做某事时,为什么要更改 list ?它给我一种感觉,好像 listtemptemp = list “链接”了。还有为什么rotate_3 ok?对不起,如果我的英语很奇怪,那不是我的第一语言(不像 Python)。

【问题讨论】:

  • 因为temp = list创建副本,不像rotate_3中的列表理解。

标签: python


【解决方案1】:

rotate_2templist 中指的是同一个列表,所以当你改变一个时,它们都会改变。

rotate_3,您正在制作副本。制作副本的一种更惯用的方式是:

temp = list[:]

我个人会这样写这个函数:

def rotate_4(l):
    return l[1:] + [l[0]]

这使用slicinglist concatenation

请注意,我已将 list 重命名为 l,因为 listbuilt-in name

【讨论】:

  • 据我了解,l = [1, 2] 在某种 Python 的柏拉图式宇宙中创建了一个列表并命名为 l,而 temp = l 只是为 提供了另一个名称 i> 列出,而l[:] 复制l 并对其进行切片?
  • @LChris314:没错。
猜你喜欢
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 2021-06-09
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多