I have a wxListBox that is filled with strings (Customer Names) that the user inputs. I have to calculate the most occurring name and least occurring name in the list. I have to use a loop.
Below is actual code mixed with pseudo code, but I am having trouble with the logic:
cust_name = ""
for names in range(self.txtListBox.GetCount()):
for compareName in counterList:
if:
names == compareName:
count += 1
else:
add names to counterList
set count to 1
What is the best way to do this with a loop in Python?
Use collections.Counter to count the names
from collections import Counter
names = ["foo","foo","foobar","foo","foobar","bar"]
c = Counter(names).most_common() # returns a list of tuples from most common to least
most_com, least_com = c[0][0],c[-1][0] # get first which is most common and last which is least
print most_com,least_com
foo bar
Using a loop, just call Counter.update
c = Counter()
for name in names:
c.update(name)
c = c.most_common()
most_com, least_com = c[0][0],c[-1][0]
If you cannot import a module use a normal dict:
d = {}
for name in names:
d.setdefault(name,0)
d[name] += 1
print d
{'foobar': 2, 'foo': 3, 'bar': 1}
srt = sorted(d.items(),key=lambda x:x[1],reverse=True)
most_com,least_com = srt[0][0],srt[-1][0]