0

我正在尝试从列表中获取一个元素并对这个元素(这也是一个列表)进行一些更改。奇怪的是,更改应用于上一个列表。这是我的代码:

>>>sentences[0]
['<s>/<s>',
 'I/PRP',
 'need/VBP',
 'to/TO',
 'have/VB',
 'dinner/NN',
 'served/VBN',
 '</s>/</s>']
>>>sentence = sentences[0]
>>>sentence.insert(0,startc); sentence.append(endc)
>>>sentences[0]
   ['<s>/<s>',
    '<s>/<s>',
    'I/PRP',
    'need/VBP',
    'to/TO',
    'have/VB',
    'dinner/NN',
    'served/VBN',
    '</s>/</s>'
    '</s>/</s>']

就像我只是得到一个指向那个元素的指针,而不是一个副本

4

2 回答 2

2

事实上,你确实得到了一个“指针”。列表(以及任何可变值类型!)在 Python 中作为引用传递。

您可以通过将列表传递给list()对象构造函数来制作列表的副本,或者使用[:].

a = [1,2,3]
b = a
c = list(a)
d = a[:]

a[1] = 4  # changes the list referenced by both 'a' and 'b', but not 'c' or 'd'
于 2013-05-11T02:29:40.783 回答
2

你完全正确!在 Python 中,当您将列表作为参数传递给函数时,或者将列表分配给另一个变量时,您实际上是在传递一个指向它的指针。

这是出于效率原因;如果您每次执行上述任何一项操作时都制作一个包含 1000 项的列表的单独副本,那么该程序将消耗太多的内存和时间。

= originalList[:]为了在 Python 中克服这个问题,您可以使用or复制一维列表= list(originalList)

sentence = sentences[0][:]     # or sentence = list(sentences[0])
sentence.insert(0,startc)
sentence.append(endc)
print(sentence)                # modified
print(sentences[0])            # not modified

如果您需要复制 2D 列表,请考虑使用列表推导。

于 2013-05-11T02:30:10.213 回答