本文介绍了Python中的条件计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定以前是否有人问过这个问题,但是我找不到明显的答案.我正在尝试计算列表中等于某个值的元素的数量.问题在于这些元素不是内置类型.所以如果我有

not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have

class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b

stuff = []
for i in range(1,10):
    stuff.append(A(i/2, i%2))

现在,我想对字段b = 1的列表元素进行计数.我想出了两种解决方案:

Now I would like a count of the list elements whose field b = 1. I came up with two solutions:

print [e.b for e in stuff].count(1)

print len([e for e in stuff if e.b == 1])

哪种方法最好?有更好的选择吗?看来count()方法不接受键(至少在Python版本2.5.1中如此.

Which is the best method? Is there a better alternative? It seems that the count() method does not accept keys (at least in Python version 2.5.1.

非常感谢!

推荐答案

sum(x.b == 1 for x in L)

布尔值(由诸如x.b == 1之类的比较得出的结果)也是int,对于False,其值为0,对于True,其值为1,因此求和之类的算法仅适用于很好.

A boolean (as resulting from comparisons such as x.b == 1) is also an int, with a value of 0 for False, 1 for True, so arithmetic such as summation works just fine.

这是最简单的代码,但可能不是最快的代码(只有timeit可以肯定地告诉您-).考虑一下(简化的大小写非常适合命令行,但等效):

This is the simplest code, but perhaps not the speediest (only timeit can tell you for sure;-). Consider (simplified case to fit well on command lines, but equivalent):

$ py26 -mtimeit -s'L=[1,2,1,3,1]*100' 'len([x for x in L if x==1])'
10000 loops, best of 3: 56.6 usec per loop
$ py26 -mtimeit -s'L=[1,2,1,3,1]*100' 'sum(x==1 for x in L)'
10000 loops, best of 3: 87.7 usec per loop

因此,在这种情况下,生成额外的临时列表并检查其长度的内存浪费"方法实际上比我倾向于的更简单,更短,更节省内存的方法要快得多.当然,列表值,Python实现,可用于加速"进行投资"的内存的可用性等其他混合因素也可能影响确切的性能.

So, for this case, the "memory wasteful" approach of generating an extra temporary list and checking its length is actually solidly faster than the simpler, shorter, memory-thrifty one I tend to prefer. Other mixes of list values, Python implementations, availability of memory to "invest" in this speedup, etc, can affect the exact performance, of course.

这篇关于Python中的条件计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:45