簡體   English   中英

Python:計算對象列表中給定屬性的不同值的數量

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

我有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)操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM