[英]Python : count the number of different values for a given attribute in a list of objects
I have a list of objects of class C
. 我有
C
类的对象列表。 Each object has an attribute attrib
. 每个对象都有一个属性
attrib
。 I want to know the number of different values attrib
can take in the list. 我想知道列表中
attrib
可以使用的不同值的数量。
This works, but it's 4 lines long. 可以,但是有4行。 Is there a way to make it shorter?
有没有办法使它更短? Nicer?
更好? More efficient?
更高效?
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
Here is one shorter version: 这是一个较短的版本:
len(set([x.attrib for x in objects]))
Regarding time complexity, you can improve your original codes from O(n^2) to O(n) by changing tmpList
to a Set. 关于时间复杂度,您可以通过将
tmpList
更改为Set来将原始代码从O(n ^ 2)改进为O(n)。 Because if o.attrib not in tmpList:
is an O(n) operation. 因为
if o.attrib not in tmpList:
则是O(n)操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.