我有一个 C
类的对象列表。每个对象都有一个属性attrib
。我想知道 attrib
在列表中可以采用的不同值的数量。
这可行,但有 4 行长。有没有办法让它变得更短?更好?效率更高?
class C:
def __init__(self, val):
self.attrib = val
# my list of objects.
# attrib is either 0, 1 or 2 (so we have 3 different values) for any object in the list
objects = [C(x % 3) for x in xrange(10)]
# Calculation :
tmpList = [] # temporary list to perform calculation
for o in objects:
if o.attrib not in tmpList :
tmpList.append(o.attrib)
print len(tmpList) # print 3
最佳答案
这是一个较短的版本:
len(set([x.attrib for x in objects]))
关于时间复杂度,您可以通过将 tmpList
更改为 Set,将原始代码从 O(n^2) 改进为 O(n)。因为 if o.attrib not in tmpList:
是一个 O(n) 操作。
关于 python : count the number of different values for a given attribute in a list of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23528497/