Search code examples
pythoncontrol-flowmultiple-conditions

Varying number of conditions


I'm working on matching input data from a form style GUI with information contained in files.

I want the use to be able to fill out one/any/all number of boxes to be matched in the files

What I think I'm looking for is something like

if ((filled_boxes[0] == file[0]) and (filled_boxes[1] == file[1]) and ....

but allow for a ranging number of conditions


Solution

  • You are probably looking for zip(), combined with all() to test for all conditions:

    if all(box ==  f for box, f in zip(filled_boxes, file)):
    

    Here zip() pairs up files and boxes, loops over each pair, and all() returns True only if all the pairs match.

    Quick demos of what zip() and all() do:

    >>> zip([1, 2, 3], ['spam', 'ham', 'eggs'])
    [(1, 'spam'), (2, 'ham'), (3, 'eggs')]
    >>> all(i < 5 for i in range(5))
    True
    >>> all(i < 5 for i in range(10))
    False
    

    where all() only needs to test enough of the generator expression to determine that there is one False value for it to return False as well.