在Python中重新分配列表的正确方法是什么? [英] What is the correct way to reassign a list in Python?

查看:85
本文介绍了在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]

这篇关于在Python中重新分配列表的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆