Python : count the number of different values for a given attribute in a list of objects

StackOverflow https://stackoverflow.com/questions/23528497

  •  17-07-2023
  •  | 
  •  

سؤال

I have a list of objects of class C. Each object has an attribute attrib. I want to know the number of different values attrib can take in the list.

This works, but it's 4 lines long. 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. Because if o.attrib not in tmpList: is an O(n) operation.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top