2012-12-30 263 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"]) 
相關問題