Ad

How To Efficiently Check For Variables In A For Loop

- 1 answer

I have eight variables that i want to check agianst the current line in the for loop. I think there might be a better way to do this than what i currently have.

I now have 5 different if statements

with open('stuff.txt', 'r') as f:
    lines = f.read().splitlines()
    for line in lines:
        if line == str(sameDay):
            bag.append(line)
        if line == str(threeDaysAgo):
            bag.append(line)
        if line == str(weekAgo):
            bag.append(line)
        if line == str(monthAgo):
            bag.append(line)
        if line == str(threeDaysAgo):
            bag.append(line)
Ad

Answer

Better than having many if statements, and also more efficient that calling on append multiple times.

variables = set(map(str, [sameDay, threeDayAgo, weekAgo...]))

def check_variables(lines):
    for line in lines:
        if line in variables:
            yield line

Edit: Made variables into a set since it runs in faster than a list. Useful if lines is really long.

Ad
source: stackoverflow.com
Ad