2021年3月20日星期六

python count ocurrences in a tuple of tuples

I have a tuple with tuples inside like this:

tup = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))  

This goes on and on and the numbers don't matter here. The only data that matters are the names. What I need is to count how many times a given name occurs in the tuple and return a list where each item is a list and the number of times it occurs, like this:

list_that_i_want = [['Joe',2],['Kevin',1],['Donald',1]]  

I don't want to use any modules or collections like Counter. I want to hard code this. I actually wanted to hardcode the full solution and not even use the '.count()' method.

So far what I got is this:

def create_list(tuples):     new_list= list()     cont = 0     for tup in tuples:         for name in tup:             name = tup[3]             cont = tup.count(name)               if name not in new_list:                 new_list.append(name)                 new_list.append(cont)     return new_list      list_that_i_want = create_list(tup)  print(list_that_i_want)    

And the output that I am been given is:

['Joe',1,'Kevin',1,'Donald',1]  

Any help? Python newbie here.

https://stackoverflow.com/questions/66728313/python-count-ocurrences-in-a-tuple-of-tuples March 21, 2021 at 10:30AM

没有评论:

发表评论