(Jan-19-2020, 01:24 AM)blackknite Wrote: So the oneliner using collections.Counter seems to be fastest, but I cant understand why and how.
How to do this better with using just simple and readable basic python?
I believe that collections.Counter (and other stuff from built-in collections module) is worth of learning and should be considered as 'simple and readable basic Python'. This is special data structure for counting and it would be non-productive to invent a wheel. Just type
help(collections.Counter)
into interactive interpreter and you get description, examples etc.If no Counter allowed or understood then it of course can be done 'manually' (and with O(n) - iterating only once over list):
>>> lst = [3,5,2,1,2,3,2,2] # list to be iterated >>> counts = dict() # dictionary for keeping counts of occurances >>> for item in lst: # iterate all list items ... try: # try +1 to value of key ... counts[item] += 1 ... except KeyError: # if key is not existing (raises KeyError) ... counts[item] = 1 # add key and set value to 1 (first count) ... >>> counts[lst[-1]] # retrieve count of last item in lst from count dict 4If try...except is not qualifying as 'simple readable and basic Python' then we can make it even simpler by not using 'advanced Python':
>>> counts = dict() >>> for item in lst: ... if item in counts: # if item already counted add one ... counts[item] += 1 ... else: # else means that first time encountered ... counts[item] = 1 # add key and set value to one ... >>> counts[lst[-1]] # get count of last item in lst 4 >>> counts # whole counts dictionary {3: 2, 5: 1, 2: 4, 1: 1}There is also collections.defaultdict but in sense of 'basic Python' it's not any better than collections.Counter.
EDIT:
And of course there is always:
>>> lst = [3,5,2,1,2,3,2,2] >>> lst.count(lst[-1]) 4
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.