例如,我们有大量这样的对象:
class KeyStatisticEntry:
def __init__(self, value=""):
self.usedBytes = len(value)
self.encoding = get_string_encoding(value)
@property
def total(self):
overhead = get_object_overhead(self.usedBytes)
if self.encoding == 'some value':
return overhead
else:
return self.usedBytes + overhead
@property
def aligned(self):
return some_func_with(self.usedBytes)
# Here is lots of calculated properties on basis of existing properties
我们需要收集大量关于这个obejct的度量-it属性的最小值、最大值、总和、平均值、标准偏差值。目前我使用的代码如下:
^{pr2}$这里有没有更“Python”的方式,性能和内存利用率更好?在
您可以使用
operator.attrgetter
来获取对象的多个属性,然后使用itertools.zip_longest
(python2.X中的itertools.izip_longest
)将相关属性附加在一起。在或者使用生成器表达式来创建生成器而不是列表:
^{pr2}$然后使用
zip_longest
:然后使用
map
函数对需要求和的iterables应用sum
函数:分别为}:
len
和{如果您想将所有子列表作为生成器处理(在内存使用方面更优化,而在运行时方面性能更低),则可以使用新类,以便使用生成器分别计算所需结果:
然后您可以:
可能有一种更好的内存使用方法,使用(隐式)生成器而不是列表来获取所有信息。我不确定如果您在同一个列表上进行许多计算(例如usedBytes),会不会更好。但是请注意,您不能在生成器上使用
len
(但是长度无论如何都是输入列表的长度):相关问题 更多 >
编程相关推荐