计算wxListBox中最常见的字符串

时间:2014-10-05 22:36:22

标签: python arrays list traversal

我有一个wxListBox,其中填充了用户输入的字符串(Customer Names)。我必须在列表中计算出现最多的名称和最少出现的名称。我必须使用一个循环。

下面是与伪代码混合的实际代码,但我遇到了逻辑问题:

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 

使用Python循环执行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

使用collections.Counter计算名称

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

使用循环,只需致电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]

如果无法导入模块,请使用普通字典:

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]