基于迭代器的方法很好。进行一些细微的修改可以强调您正在计数的事实:
sum(1 if meets_condition(x) else 0 for x in my_list)# or sum(1 for x in my_list if meets_condition(x))
和往常一样,如果意图从代码中不明显,则将其封装在描述性命名的函数中:
def count_matching(condition, seq): """Returns the amount of items in seq that return true from condition""" return sum(1 for item in seq if condition(item))count_matching(meets_condition, my_list)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)