gpt4 book ai didi

python - 更新一个实例属性的最有效方法

转载 作者:行者123 更新时间:2023-11-30 23:58:43 24 4
gpt4 key购买 nike

我正在创建任意数量的实例(使用 for 循环和范围)。在将来的某些事件中,我只需要更改其中一个实例的属性。最好的方法是什么?

现在,我正在执行以下操作:
1) 管理列表中的实例。
2) 迭代列表以查找键值。
3)一旦我在列表中找到正确的对象(即键值=我正在寻找的值),更改我需要更改的任何属性。

for Instance within ListofInstances:
if Instance.KeyValue == SearchValue:
Instance.AttributeToChange = 10

这感觉效率很低:我基本上是在迭代整个实例列表,即使我只需要更改其中一个实例的属性。

我是否应该将实例引用存储在更适合随机访问的结构中(例如以 KeyValue 作为字典键的字典?)在这种情况下字典是否更有效?我应该使用其他东西吗?

谢谢,
迈克

最佳答案

Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?)

是的,如果您从一个键映射到一个值(在本例中就是这样),这样人们通常通过其键访问一个元素,那么 dict而不是列表更好。

Is a dictionary any more efficient in this case?

是的,它效率更高。字典通过键查找项目平均需要 O(1) 时间,而列表通过键查找项目平均需要 O(n) 时间,这就是您当前正在做的事情。

使用字典

 # Construct the dictionary
d = {}

# Insert items into the dictionary
d[key1] = value1
d[key2] = value2
# ...

# Checking if an item exists
if key in d:
# Do something requiring d[key]
# such as updating an attribute:
d[key].attr = val

关于python - 更新一个实例属性的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2894733/

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