[英]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
. 该对象还有另外两个可迭代对象
b
和c
作为属性one
和two
传递给它。
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.