您还可以通过只访问一次e.tid、e.yes_count 和e.no_count 并将它们存储在变量中来节省一些时间:
for e in entries:
tid = e.tid
if tid in tids:
yes_count = e.yes_count
no_count = e.no_count
if yes_count > 0 or no_count > 0:
ratio = yes_count / (yes_count + no_count)
if ratio > 0.75:
yes_entries.append(tid)
elif ratio < 0.25:
no_entries.append(tid)
您还可以通过缓存 no_entries.append 和 yes_entries.append 来节省时间:
yes_entries_append = yes_entries.append
no_entries_append = no_entries.append
for e in entries:
tid = e.tid
if tid in tids:
yes_count = e.yes_count
no_count = e.no_count
if yes_count > 0 or no_count > 0:
ratio = yes_count / (yes_count + no_count)
if ratio > 0.75:
yes_entries_append(tid)
elif ratio < 0.25:
no_entries_append(tid)
但到那时,你可能开始变得愚蠢了。
另一个可能更愚蠢的尝试是看看使用过滤器是否更快。在 python2 中, filter 返回一个列表,这意味着您要对其进行两次迭代,这不太理想。但是,我们有 itertools 来帮助我们:
def filterfunc(e):
return (e.tid in tids) and (yes_count > 0 or no_count > 0)
for e in itertools.ifilter(filterfunc, entries):
tid = e.tid
yes_count = e.yes_count
no_count = e.no_count
ratio = yes_count / (yes_count + no_count)
if ratio > 0.75:
yes_entries_append(tid)
elif ratio < 0.25:
no_entries_append(tid)
下一个问题是我们再次访问 e 上的字段两次。让我们用一些迭代器魔法来解决这个问题:
def filterfunc(t):
tid, yes_count, no_count = t
return (tid in tids) and (yes_count > 0 or no_count > 0)
for tid, yes_count, no_count in itertools.ifilter(filterfunc, itertools.imap(attrgetter(["tid", "yes_count", "no_count"]), entries)):
ratio = yes_count / (yes_count + no_count)
if ratio > 0.75:
yes_entries_append(tid)
elif ratio < 0.25:
no_entries_append(tid)
由您和您的分析器从我建议的所有选项中确定最佳方法。
另外,如果您使用的是 python3,请使用 filter 而不是 itertools.ifilter,因为它返回的是生成器而不是 python2 的版本列表。