我已经实现了以下代码,它完美无缺地运行。但我对它不满意,因为它看起来不漂亮?最重要的是,我觉得它看起来不像pythonic方式。
所以我想我会从stackoverflow社区获取建议。这个metod是从sql查询中获取数据的,这是另一个方法,该方法返回一个字典并根据该字典中的数据进行模式匹配和计数过程。我想以pythonic方式执行此操作并返回更好的数据结构。
以下是代码:
def getLaguageUserCount(self):
bots = self.getBotUsers()
user_template_dic = self.getEnglishTemplateUsers()
print user_template_dic
user_by_language = {}
en1Users = []
en2Users = []
en3Users=[]
en3Users=[]
en4Users=[]
en5Users=[]
en_N_Users=[]
en1 = 0
en2 = 0
en3 = 0
en4 = 0
en5 = 0
enN = 0
lang_regx = re.compile(r'User_en-([1-5n])', re.M|re.I)
for userId, langCode in user_template_dic.iteritems():
if userId not in bots:
print 'printing key value'
for item in langCode:
item = item.replace('--','-')
match_lang_obj = lang_regx.match(item)
if match_lang_obj is not None:
if match_lang_obj.group(1) == '1':
en1 += 1
en1Users.append(userId)
if match_lang_obj.group(1) == '2':
en2 += 1
en2Users.append(userId)
if match_lang_obj.group(1) == '3':
en3 += 1
en3Users.append(userId)
if match_lang_obj.group(1) == '4':
en4 += 1
en4Users.append(userId)
if match_lang_obj.group(1) == '5':
en5 += 1
en5Users.append(userId)
if match_lang_obj.group(1) == 'N':
enN += 1
en_N_Users.append(userId)
else:
print "Group didn't match our regex: " + item
else:
print userId + ' is a bot'
language_count = {}
user_by_language['en-1-users'] = en1Users
user_by_language['en-2-users'] = en2Users
user_by_language['en-3-users'] = en3Users
user_by_language['en-4-users'] = en4Users
user_by_language['en-5-users'] = en5Users
user_by_language['en-N-users'] = en_N_Users
user_by_language['en-1'] = en1
user_by_language['en-2'] = en2
user_by_language['en-3'] = en3
user_by_language['en-4'] = en4
user_by_language['en-5'] = en5
user_by_language['en-n'] = enN
return user_by_language
答案 0 :(得分:3)
您可以避免所有这些列表,并将数据直接添加到user_by_language
词典。
我将其定义为:
user_by_language = collections.defaultdict(list)
匹配正则表达式后,只需执行以下操作:
user_by_language['en-%s-users' % match_lang_obj.group(1)].append(userId)
最后,您抓住这些元素的所有长度并将其保存为en-1
,en-2
...