Skip to content
Advertisement

Is there a way to make this “for loop” cleaner in Python?

I created a simple script that goes to a notepad file, reads it line by line and if it finds certain words it adds to a counter. Then at the end it spits out the final count for each word.

The current implementation works, I just know it’s not the most efficient way of doing things. I would love for someone with more experience to see if there is a simple FOR loop that can reduce the need of having 60 rows of the same thing. I am currently very inexperienced in Python and I’d love to find more efficient ways to do the same thing, this would help me learn new things

The code is here (it’s long but just because I’m writing everything out manually, my goal is to accomplish the same thing with just a few lines using for loops)

JavaScript

Thank you!

Advertisement

Answer

you could use a list for your items then a dict for the counts. for each rep in the counts dict check if it exists in the line.

JavaScript

SAMPLE DATA

JavaScript

OUTPUT

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement