简体   繁体   English

Python方式遍历对象属性并分配新属性

[英]Pythonic way to to loop through object attributes and assign new attribute

I am working with a large object a in Python. 我有一个大对象工作a在Python。 The object has two other iterable objects b and c passed to it as attributes one and two . 该对象还有另外两个可迭代对象bc作为属性onetwo传递给它。

I want to consolidate the important data in the object prior to passing it to the templating engine. 我想先将对象中的重要数据合并,然后再将其传递给模板引擎。 I am trying to take an attribute from one and assign it to two . 我试图从one属性,并将其分配给two

My first thought was to parse the two objects with two stacked for loops like this.. 我的第一个想法是使用两个堆叠的for循环解析两个对象。

for c in a.two:
    for a in a.one:
        if a.id == c.id:
            setattr(c, 'title', a.title)

However, I am not sure if this is the most pythonic way of doing this. 但是,我不确定这是否是最Python化的方法。

You can improve your code from a time complexity of O(nxm) to O(n + m) (quadratic to linear) by building a dict for each list that maps the id s of objects in the list to the objects, and using set intersection between the dict keys to find the common id s between the two lists instead. 通过为每个列表构建一个将列表中的对象id映射到对象的列表的字典,并使用set,可以将代码从O(nxm)O(n + m) (二次到线性)的时间复杂度提高。 dict键之间的交集来查找两个列表之间的公共id Also, you don't need to use the setattr function if the attribute name you're setting is fixed; 另外,如果要设置的属性名称是固定的,则无需使用setattr函数。 you can assign to the object's attribute directly instead: 您可以改为直接分配给对象的属性:

one = {obj.id: obj for obj in a.one}
two = {obj.id: obj for obj in a.two}
for id in set(one).intersection(two):
    two[id].title = one[id].title

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:循环并分配嵌套对象属性的简单方法? - Python: easy way to loop through and assign nested object attributes? 将参数分配到属性的Pythonic方法? - Pythonic way to assign the parameter into attribute? 分配和访问可为空对象的大多数pythonic方法 - Most pythonic way to assign and access a nullable object 导入和使用数据作为对象属性的Python方法 - Pythonic way to import and use data as object attributes 有没有办法遍历数据框并根据列表在新列中分配值? - Is there a way to loop through a dataframe and assign a value in a new column based on a list? 从 Python object 获取两个属性之一的 Pythonic 方式 - Pythonic way to get either one of two attributes from a Python object 将类型信息添加到对象属性的pythonic方法是什么? - What is the pythonic way to add type information to an object's attributes? 在完全初始化之前引用对象属性的更多pythonic方式 - More pythonic way of referencing an object's attributes before it is completely initialized 是否有一种pythonic方式可以知道for中的第一个和最后一个循环何时通过? - Is there a pythonic way of knowing when the first and last loop in a for is being passed through? Pythonic 遍历字典并执行条件 GET 请求的方法 - Pythonic way to loop through dictionary and perform conditional GET request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM