I'm trying to to sort through a file line by line, comparing the beginning with a string from a list, like so:
for line in lines:
skip_line = True
for tag in tags:
if line.startswith(tag) is False:
continue
else:
skip_line = False
break
if skip_line is False:
#do stuff
While the code works just fine, I'm wondering if there's a neater way to check for this condition. I have looked at any()
, but it seems to just give me the possibility to check if any of my lines start with a fixed tag (not eliminating the for
loop needed to loop through my list.
So, essentially I'm asking this:
Is there a better, sleeker option than using a for loop to iterate over my tags
list to check if the current line starts with one of its elements?
As Paradox pointed out in his answer: Using a dictionary to lookup if the string exists has O(1) complexity and actually makes the entire code look a lot cleaner, while being faster than looping through a list. Like so:
tags = {'ticker':0, 'orderBook':0, 'tradeHistory':0}
for line in lines:
if line.split('\t')[0] in tags:
#do stuff