gpt4 book ai didi

python - 在 Python 程序中处理大量对象

转载 作者:太空宇宙 更新时间:2023-11-03 12:04:02 24 4
gpt4 key购买 nike

我正在构建一个 python 程序,它将处理数千个 python 对象。我很好奇什么是组织它们的最优雅的方式,而且我也不清楚什么时候在 python 中复制了东西。

例如,如果我有一个管理器对象,其中包含数千个对象的列表,但它也有一个字典,其中包含这数千个对象中每一个的键,这些对象是否在内存中存在两次?如果我要更改列表中对象的属性,它是否也会更改字典中相应对象的属性?

我找不到太多关于此的好读物,所以如果有人能给我指出正确的方向,那将会很有帮助。

这是我的想法:

class Manager():
def __init__(self,list_of_objects):
self.myobjects = []
self.myobjectsdict= {}

self.myobjects = list_of_objects

for object in self.myobjects:
self.myobjectsdict[object.name] = object

然后,如果我要创建第二个管理器对象并给它一些第一个管理器的对象,它们会是副本吗?或者第二位经理所做的更改是否适用于第一位经理所欠的对象?例如,这里发生了什么:

manager2 = Manager(manager1.myobjects[5000:10000])
manager2.myobjects[71].name = "newname"

第一个管理器中该对象的名称是否发生变化?字典键仍然是旧名称吗?

最后,包含数千个对象的列表或字典真的是组织大量 python 对象的最佳方式吗?或者有没有更好的方式我还没有遇到过?非常感谢您的帮助。

最佳答案

This post讨论通过引用传递变量(Python 通过赋值传递)。

[If] I have a manager object which has a list of thousands of objects, but it also has a dictionary with keys to each of those thousands of objects, do the objects exist twice in memory? If I were to change the properties of an object in the list, will it also change the properties of the corresponding object in the dict?

当您通常将对象名称用作字典中的键或值时,您传递的是对该对象的引用。如果您要更新对象中的 some 值,字典(或列表)中的值也会更新。

>>> my_object = MyClass() # Myclass is instantiated with x = 10
>>> my_dict = {"my_obj":my_object}
>>> my_dict["my_obj"] is my_object
True
>>> my_dict["my_obj"].x
10

如果你将这个字典放在一个对象中,它的行为方式是一样的。

Then, if I were to create a second manager object and give it some of the first manager's objects, would they be copies?

不,它们也是引用。如果您更改其中一位经理的姓名,那么另一位经理也会受到影响。

Finally, is a list or dict of thousands of objects really the best way to organize lots of python objects, or is there a better way I haven't come across?

您将 Python 对象用于什么目的?你需要遍历它们吗?您是否尝试根据某些条件过滤对象?您是否需要快速检查某些值是否存在?是否有必要在内存中保留数千个对象?

如果没有更多信息,这部分问题就不容易回答。

关于python - 在 Python 程序中处理大量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38176794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com