-5

I have a nested list that contains 2 names and 2 ages respectively. I need to write a function that looks through the list and counts the number of times the name appears. The list looks like this:

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

So this function would count that James is in the list twice, Alan twice, and the rest of the names once.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    I'm afraid to tell you you're asking your question in a wrong place. If you want to get your desire answer you better to update your question with the code that you've tried so far and tell us about it's problems. – Mazdak May 08 '17 at 08:56
  • It's unclear what your specific problem is. You want to write this function, but at what point did you get stuck? Your requirements are unclear as well. Should the function return counts for _all_ names or just for one of the names that is passed in as a parameter? – Sven Marnach May 08 '17 at 09:00

2 Answers2

3

To count things, I'd suggest a 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})
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
1

This code works

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

Edit 1: If you don't know the name you are searching for and want all the count of the names,then this code works

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
bigbounty
  • 16,526
  • 5
  • 37
  • 65
  • Is there a way I can do it so that I don't have to include 'James' in my code? So if the list was a lot larger and I didn't know all the names it would still count them. – Henry Jones May 08 '17 at 08:58
  • Then use dictionary.So,when you see a new name add it to the dictionary as the key and increment the value for that key i.e name – bigbounty May 08 '17 at 08:59