2014-10-05 24 views
0

我有一個填充了用戶輸入的字符串(客戶名稱)的wxListBox。我必須計算列表中最常出現的名稱和最少出現的名稱。我必須使用循環。計算wxListBox中最常見的字符串

下面是實際的代碼與僞代碼喜憂參半,但我有邏輯的麻煩:

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

使用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] 
+0

這絕對是最簡單的方法,但我應該使用循環。 – 2014-10-05 22:43:49

+0

你仍然可以使用循環,只需使用c.update(name) – 2014-10-05 22:46:20

+0

真棒,感謝@Padraic – 2014-10-05 22:56:23