我有一列数据(可以通过gspread轻松从Google文档中导入),我希望能够智能地对齐。我将条目录入字典中。输入可以包括电子邮件,推特句柄或博客URL。例如:
mike.j@gmail.com
@mikej45
j.mike@world.eu
_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
在if过程中添加一些智能的有效(-ish)方法是什么?
答案 0 :(得分:1)
您可以尝试使用defaultdict:
from collections import defaultdict
unique_nominees = defaultdict(lambda: 0)
unique_nominees[c] += 1