将列表中的多个元素添加到list.count(Python)

将列表中的多个元素添加到list.count(Python),list,python-2.7,List,Python 2.7,抱歉标题有些模糊,我会在这里解释更多 目前,我有以下代码,它计算值“y”和“n”在名为“results”的列表中出现的次数 是否有一种方法可以使“是”这样的值也计入NumberOfA?我的想法大致如下: NumberOfA = results.count("y" and "yes" and "Yes") NumberOfB = results.count("n" and "no" and "No") 但这不起作用。这可能是一个很容易解决的问题,但是嘿。提前谢谢 至于您上面的答案为什么不起作用,

抱歉标题有些模糊,我会在这里解释更多

目前,我有以下代码,它计算值“y”和“n”在名为“results”的列表中出现的次数

是否有一种方法可以使“是”这样的值也计入NumberOfA?我的想法大致如下:

NumberOfA = results.count("y" and "yes" and "Yes")
NumberOfB = results.count("n" and "no" and "No")

但这不起作用。这可能是一个很容易解决的问题,但是嘿。提前谢谢

至于您上面的答案为什么不起作用,这是因为Python只会获取您传入的表达式的最终值:

>>> 'Yes' and 'y' and 'yes'
'yes'
因此,您的
计数将关闭,因为它只是在寻找最终值:

>>> results.count('yes' and 'y')
1
>>> results.count('yes' and '???')
0
你喜欢这个工作吗?请注意,这取决于他们在列表中只有是/否的答案(如果列表中有“是……嗯,否”之类的内容,则答案将是错误的):

一般的想法是,获取结果列表,然后遍历每个项目,将其小写,然后获取第一个字母(
startswith
)-如果字母是
y
,我们知道它是
yes
;否则,它将是

如果需要的话,还可以通过执行类似的操作来组合上述步骤(注意,这需要Python 2.7):

计数器
对象可以像字典一样处理,因此您现在基本上拥有一个包含
计数的字典。

创建一个方法

NumberOfA = results.count("y") + results.count("yes") + results.count("Yes")
NumberOfB = results.count("n") + results.count("no") + results.count("No")
def multiCount(lstToCount, lstToLookFor):
    total = 0
    for toLookFor in lstToLookFor:
        total = total + lstToCount.count(toLookFor)
    return total
然后


我只是在这里得到一种模板;最终,它将接受任何和所有问题,以及答案的选择,而不仅仅是“是”和“否”。不过,这是解决我目前问题的一个非常好的方法。我喜欢@dantdj啊,我明白了-无论如何,很高兴它起了作用!
计数器
功能在很多情况下都非常有用,因此如果可能的话,肯定有值得探索的地方。祝你万事如意!
>>> from collections import Counter
>>> results = ['yes', 'y', 'Yes', 'no', 'NO', 'n']
>>> Counter((x.lower()[0] for x in results))
Counter({'y': 3, 'n': 3})
NumberOfA = results.count("y") + results.count("yes") + results.count("Yes")
NumberOfB = results.count("n") + results.count("no") + results.count("No")
def multiCount(lstToCount, lstToLookFor):
    total = 0
    for toLookFor in lstToLookFor:
        total = total + lstToCount.count(toLookFor)
    return total
NumberOfA = multiCount(results, ["y", "yes", "Yes"])
NumberOfB = multiCount(results, ["n", "no", "No"])