2012-11-26 53 views
0

我有一列我想智能對齊的數據(從Google文檔輕鬆導入,感謝gspread)。我將條目攝入字典中。輸入可以包括電子郵件,推特處理或博客URL。例如:Python中的索引類似條目

[email protected]
@mikej45
[email protected]
_http://tumblr.com/mikej45

眼下, 「啞」 的版本是:

def NomineeCount(spreadsheet): 
    worksheet = spreadsheet.sheet1 
    nominees = worksheet.col_values(6) # F = 6 
    unique_nominees = {} 
    for c in nominees: 
     pattern = re.compile(r'\s+') 
     c = re.sub(pattern, '', c) 
     if unique_nominees.has_key(c) == True: # If we already have the name 
      unique_nominees[c] += 1 
     else: 
      unique_nominees[c] = 1 

     # Print out the alphabetical list of nominees with leading vote count 
     for w in sorted(unique_nominees.keys()): 
     print string.rjust(str(unique_nominees[w]), 2)+ " " + w 

     return nominees 

什麼時,如果處理的高效(-ish)的方式在一些智慧補充的嗎?

回答

1

您可以defaultdict嘗試:

from collections import defaultdict 
unique_nominees = defaultdict(lambda: 0) 
unique_nominees[c] += 1