我想计算列表项满足一个条件的次数。例如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
答案 0 :(得分:3)
你可以使用列表理解 - 奖励积分,因为它们很快(列表补偿用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