如何从列表中获取副本?

2024-06-16 09:51:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

>>>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>']

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


Tags: to元素列表havesentencesnnneedsentence
2条回答

你说得对!在Python中,当您将一个列表作为参数传递给函数,或者将一个列表赋给另一个变量时,实际上是在传递一个指向它的指针。你知道吗

这是为了提高效率;如果每次执行上述操作时都单独复制一份1000项列表,那么程序将消耗太多的内存和时间。你知道吗

为了在Python中克服这个问题,可以使用= originalList[:]= 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列表,可以考虑使用list comprehension。你知道吗

事实上,你得到了一个“指针”。列表(以及任何可变值类型!)在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'

相关问题 更多 >