2017-05-08 94 views
-6

我有一個嵌套列表,分別包含2個名稱和2個年齡段。我需要編寫一個函數,查看列表並計算名稱出現的次數。該列表如下所示:計算嵌套列表中的重現

L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']] 

所以這個函數會計算James在列表中兩次,Alan在兩次,而其他名字在一次。

+1

我不敢告訴你你問你的問題在一個錯誤的地方。如果你想得到你想要的答案,最好用迄今爲止嘗試過的代碼更新你的問題,並告訴我們它的問題。 – Kasramvd

+0

目前還不清楚你的具體問題是什麼。你想寫這個函數,但是你在什麼時候卡住了?您的要求也不清楚。函數返回值是否應該爲_all_名稱計數,或者只是作爲參數傳入的名稱之一? –

回答

0

此代碼的工作

L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], 
    ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']] 
name = 'James' 
count = 0 
for nested_list in L: 
    if name in nested_list: 
     count+=1 
print count 

編輯1: 如果你不知道你正在搜索的名稱,並希望該名稱的所有數量,那麼這個代碼工作

L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], 
['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']] 
count_dict = {} 

for nested_list in L: 
    if nested_list[0] not in count_dict.keys(): 
     count_dict[nested_list[0]] = 0 
    elif nested_list[1] not in count_dict.keys(): 
     count_dict[nested_list[1]] = 0 
    count_dict[nested_list[0]] += 1 
    count_dict[nested_list[1]] += 1 


for key,value in count_dict.items(): 
    print 'Name:',key,'Occurrence count',value 
+0

有沒有辦法讓我做到這一點,這樣我就不必在代碼中包含'James'了?所以如果名單更大,我不知道所有的名字,它仍然會計數。 –

+0

然後使用dictionary.So,當你看到一個新名字時,將它作爲鍵添加到詞典中,並遞增該鍵的值,即名稱 – bigbounty

3

要計算的東西,我會建議一個Counter

>>> from collections import Counter 
>>> L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']] 
>>> Counter(name for sub_list in L for name in sub_list[:2]) 
Counter({'James': 2, 'Alan': 2, 'Phil': 1, 'Bill': 1, 'Hillary': 1, 'Henry': 1}) 
+0

這很有幫助:)謝謝 –