在Python中重新分配列表的正确方法是什么?

在Python中重新分配列表的正确方法是什么?

问题描述:

我应该;

a = range(100)
old_list = filter(lambda x: x not in a, old_list)
a = range(200)
old_list = filter(lambda x: x not in a, old_list)

或:

a = range(100)
old_list = filter(lambda x: x not in a, old_list)
a[:] = range(200)
old_list = filter(lambda x: x not in a, old_list)

更重要的是,这有关系吗?首先,元素中的元素是否被释放,它们的引用计数是否为0?还是程序仍然需要引用它.如果是这样,我将完全覆盖第二个示例中的引用.

And more importantly, does it matter? In the first, are the elements in a freed, is their reference count 0? Or do the program still need the references to it. If so, I'm completely overwriting the references in the second example.

两种方法均有效.它们之间有细微的差别:

Both ways are valid. There is a subtle difference between them:

  • 第一个创建一个全新的列表对象a.
  • 第二个替换现有列表对象a中的所有元素.
  • The first creates a completely new list object a.
  • The second replaces all elements in the existing list object a.

以下两个片段演示了区别:

The following two snippets demonstrate the difference:

# #1
a = range(3)
b = a
a = range(5)
print b

# #2
a = range(3)
b = a
a[:] = range(5)
print b

第一个打印出来

[0, 1, 2]

第二个打印出来

[0, 1, 2, 3, 4]