Search code examples
pythonlistfilestring-matchingany

Python - If any element in list is in line


So I have some code here:

for line in FlyessInput:
if any(e in line for e in Fly):
    FlyMatchedOutput.write(line)
elif line not in Fly:
    FlyNotMatchedOutput.write(line)
else:
    sys.exit("Error")

And for some reason, instead of outputting the lines which are matched in the List 'Fly', they only output the lines which appear in the FlyessInput file and not all of them. It does not seem to have a consistent output.

What I want is for each line which matches an element in 'Fly' to be outputted into FlyMatchedOutput. I have checked the input file and the 'Fly' list and there are elements which match but they do not seem to be sent to the MatchedOutput File.

Thanks, Nick.


Solution

  • What I want is for each line which matches an element in 'Fly' to be outputted into FlyMatchedOutput.

    I don't think your elif does what you think it should, but not knowing your test input I can't say if that's causing problems.

    Here's a slight change to your code that seems to do what you want( though priting instead of calling your other functions.

    def testFlyCode(FlyessInput, Fly):
        for line in FlyessInput:
            if any(e in line for e in Fly):
                print('FlyMatchedOutput', line)
            else:
                print('FlyNotMatchedOutput', line)
    
    FlyessInput = [[1, 2, 3], [2, 3, 4]]
    Fly = [1, 2]
    testFlyCode(FlyessInput, Fly)
    
    Fly = [1, 12]
    testFlyCode(FlyessInput, Fly)
    

    output:

    ('FlyMatchedOutput', [1, 2, 3])
    ('FlyMatchedOutput', [2, 3, 4])
    ('FlyMatchedOutput', [1, 2, 3])
    ('FlyNotMatchedOutput', [2, 3, 4])