2012-12-30 201 views
2

道歉有些模糊的标题,我会在这里尝试解释更多。将一个列表中的多个元素添加到list.count(Python)

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

NumberOfA = results.count("y") 
NumberOfB = results.count("n") 

是否有一种方法可以使例如“是”之类的值也计入NumberOfA?我在想以下几点:

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

但这并不奏效。这可能是一个很容易解决的问题,但是,嘿。提前致谢!

回答

1

至于为什么你上面的答案是不行的,这是因为Python将只需要你通过表达的终值:

>>> 'Yes' and 'y' and 'yes' 
'yes' 

因此您count将被关闭,因为它只是在寻找最终值:

>>> results.count('yes' and 'y') 
1 
>>> results.count('yes' and '???') 
0 

会是这样的工作?请注意,这取决于他们的唯一的结果为YES /列表中没有式的答案(将是错误的,如果事情像“啊....嗯没有”都在那里):

In [1]: results = ['yes', 'y', 'Yes', 'no', 'NO', 'n'] 

In [2]: yes = sum(1 for x in results if x.lower().startswith('y')) 

In [3]: no = sum(1 for x in results if x.lower().startswith('n')) 

In [4]: print yes, no 
3 3 

的总体思路是:把你的结果清单,然后遍历每个项目,降低它,然后采取第一个字母(startswith) - 如果该字母是y,我们知道它是一个yes;否则,它将是no

您还可以通过做这样的事情(注意这需要Python 2.7)结合起来,如果你想上面的步骤:

>>> from collections import Counter 
>>> results = ['yes', 'y', 'Yes', 'no', 'NO', 'n'] 
>>> Counter((x.lower()[0] for x in results)) 
Counter({'y': 3, 'n': 3}) 

Counter对象是可以治疗的,就像字典,所以你现在基本上是有包含了yes's和no的字典。

+0

我刚开始是一种模板到这里;最终它会带着任何和所有的问题,以及选择的答案,而不仅仅是“是”和“否”。不过,这是解决我当前问题的一个非常好的方法。我喜欢! – dantdj

+0

@dantdj啊呃 - 无论如何,很高兴它帮助! “计数器”功能在许多情况下可以超级有用,所以如果可能的话,绝对值得探索。祝你一切顺利! – RocketDonkey

1
NumberOfA = results.count("y") + results.count("yes") + results.count("Yes") 
NumberOfB = results.count("n") + results.count("no") + results.count("No") 
0

创建方法

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"]) 
相关问题