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

标签 python list count attributes

我有一个 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/

相关文章:

Mysql COUNT VS num rows 性能

python - Virtualenv 没有安装 pip

Python Selenium WebDriver - 可以监视 XHR AJAX 调用吗?

python - 获取Google搜索结果和清理HTML标签的建议

python - 如何获得通过给定点的嵌套列表的对角线 - Python

使用 COUNT (DISTINCT obj) 生成 JPA native 查询

python - 如何在 PyTorch 中获得导数的完整雅可比行列式?

java - ArrayIndexOutOfBoundsException :-1

python - 如何将列表中的两个相邻元素相乘?

java - 使用Java在DynamoDb中找不到QueryRequest的SetCount方法