如何优化Python中统计指定词汇的冗余for循环代码?
更简洁高效的Python词汇统计实现
Hey there! Let's fix that repetitive code and make your script way cleaner and scalable. The biggest issue with your current approach is all the hardcoded variables and endless elif checks—we can replace that with dictionaries and lists to eliminate redundancy entirely.
改进思路
Instead of creating separate variables for each rep and their count, we'll:
- Store all target reps in a single list (easy to update later)
- Use a dictionary to track counts for each rep (no more
rep1count,rep2count, etc.) - Use simple loops to check each word against our target list, with just one conditional check
优化后的代码
location = "X:\\Sales\\Shortcuts\\ShiftReportsIL.txt" # 把所有需要统计的用户名放到一个列表里,新增/删除直接改这里 target_reps = [ "ttsachev", "vpopov", "alupashko", "ekarachorova", "glipchev", "ggeorgiev", "syovcheva", "vpanchev", "vbimbalova", "hmarinov", "fr-egonzalez", "dvaldenegro", "ndinev", "apiera", "csehunoe", "dbolingo", "mmamatela", "enter new rep here", "enter new rep here" ] # 用字典推导式初始化每个rep的计数为0 rep_counts = {rep: 0 for rep in target_reps} def count_reps(): # with语句会自动关闭文件,不用手动调用f.close() with open(location, 'r', encoding="utf8", errors='ignore') as f: # 直接遍历文件行,不用readlines()(更节省内存) for line in f: words = line.lower().split() for word in words: # 只需要一个判断:如果单词在我们的目标字典里,计数加1 if word in rep_counts: rep_counts[word] += 1 # 调用统计函数 count_reps() # 遍历字典输出所有结果 for rep, count in rep_counts.items(): print(f"{rep}: {count}")
关键改进点
- No more repetitive variables: Adding a new rep only requires adding their name to the
target_repslist—no need to create new count variables or add anotherelifcheck. - Cleaner logic: The single
if word in rep_countsreplaces your 19 conditional checks, making the code easier to read and maintain. - Better file handling: The
withstatement automatically closes the file when done, which is safer than manually callingf.close()(your original code even missed the parentheses here, so it wasn't actually closing the file!). - Scalable: This approach works no matter how many reps you need to add—you won't have to rewrite half the script to expand it.
额外小优化(可选)
If you want to avoid counting duplicate entries in target_reps (like the two "enter new rep here" entries), you can convert the list to a set first when initializing the dictionary:
rep_counts = {rep: 0 for rep in set(target_reps)}
This will ensure each rep only has one entry in the count dictionary.
内容的提问来源于stack exchange,提问作者Joseph Harari
相关产品推荐
相关产品推荐

