enumerate 可以用来统计某些条件的发生次数吗?

Can enumerate be used to count the occurrence of some condition?

我想计算列表中的项目满足一个条件的次数。例如 a[i] > 1:

a = [2,4,3,0]

counter = 0
for value in a:
    if value > 1:
        counter += 1

是否可以使用enumerate函数来避免计数器+=1?

在循环中进行:

for i,j in enumerate(list(xrange(5))):
    print i
    print j

您可以使用列表理解 - 加分,因为它们非常快(列表组合是用 C 实现的)

a = [2,3,4,0]
count = len([i for i in a if i > 1])
# Or, to avoid a temporary list: (courtesy of John Kugelman)
count = sum(1 for i in a if i > 1)

解释:

len(...) # Gives the number of terms in the list
[i for i in a ... ] # Works like a for loop- this list is composed of pieces named i, where
                    # i is each term in a
[ ... if i > 1] # As long as that i is > 1.

# The sum() method does the same thing, but slightly more memory-efficient