组合多个对象并在python中创建重叠属性列表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了组合多个对象并在python中创建重叠属性列表相关的知识,希望对你有一定的参考价值。
我有一个类如下:
class test(object):
def __init__(self, ID, A, B, C, D, E):
self.ID = ID
self.A = A
self.B = B
self.C = C
self.D = D
self.E = E
列表中的多个对象:
test1 = test(6124, 6, 'Tim', 'Football', 'Soccer', 'USA')
test2 = test(6124, 7, 'Joe', 'Basketball', 'Soccer', 'USA')
test3 = test(6188, 8, 'Joe', 'Basketball', 'Soccer', 'USA')
test4 = test(6188, 9, 'Joe', 'Basketball', 'Soccer', 'USA')
test5 = test(6188, 10, 'Tim', 'Football', 'Soccer', 'USA')
objects_list = [test1, test2, test3, test4, test5]
我想基于它们的ID属性合并这些对象,对于其余属性,只需列出各个对象:
对于此示例,结果将是两个对象(仅作为两个唯一ID),其中一个具有属性:
self.ID = 6124
self.A = [6, 7]
self.B = ['Tim', 'Joe']
self.C = ['Football', 'Basketball']
self.D = ['Soccer', 'Soccer']
self.E = ['USA', 'USA]
如何以这种方式合并列表中的对象?我正在寻找一个解决方案,它不需要我命名任何属性,但我要合并的属性的名称(ID
)。如果这个解决方案可以被推广到一次合并多个属性(比如ID
和A
和E
),那将是特别好的。
谢谢!插口
答案
尝试此解决方案:
from operator import attrgetter
from itertools import groupby
class Test(object):
def __init__(self, ID, A, B, C, D, E):
self.ID = ID
self.A = A
self.B = B
self.C = C
self.D = D
self.E = E
test1 = Test(6124, 6, 'Tim', 'Football', 'Soccer', 'USA')
test2 = Test(6124, 7, 'Joe', 'Basketball', 'Soccer', 'USA')
test3 = Test(6188, 8, 'Joe', 'Basketball', 'Soccer', 'USA')
test4 = Test(6188, 9, 'Joe', 'Basketball', 'Soccer', 'USA')
test5 = Test(6188, 10, 'Tim', 'Football', 'Soccer', 'USA')
objects_list = [test1, test2, test3, test4, test5]
# get names of attributes except 'ID'
attrs = list(x for x in dir(test1) if not x.startswith('__') and x != 'ID')
# iterate through grouped by 'ID' elements
for id_, group in groupby(sorted(objects_list, key=attrgetter('ID')),
key=attrgetter('ID')):
# create result object with lists as attributes
result = Test(id_, *[[]]*len(attrs))
# merge elements
for x in group:
for a in attrs:
setattr(result, a, getattr(result, a) + [getattr(x, a)])
print(result.ID, result.A, result.B, result.C, result.D, result.E)
结果:
6124 [6, 7] ['Tim', 'Joe'] ['Football', 'Basketball'] ['Soccer', 'Soccer'] ['USA', 'USA']
6188 [8, 9, 10] ['Joe', 'Joe', 'Tim'] ['Basketball', 'Basketball', 'Football'] ['Soccer', 'Soccer', 'Soccer'] ['USA', 'USA', 'USA']
以上是关于组合多个对象并在python中创建重叠属性列表的主要内容,如果未能解决你的问题,请参考以下文章