Search code examples
pythonenumerate

How i can set the increasing of enumerate, that depends on condition?


I have got the following loop^

i = 0
for var in vars:
    if var[ "ID" ] != 0 and var[ "ID" ] & 1:
        print i, var[ "ID" ]
        i += 1      

Can I use enumerate for this loop instead of counter i ? How i can set the increasing of enumerate, that depends on this condition: if var[ "ID" ] != 0 and var[ "ID" ] & 1:


Solution

  • You may use filter:

    >>> vs = [{'ID': 1}, {'ID': 4}]
    >>> for i, v in enumerate(filter(lambda x: x['ID'] & 1, vs)):
    ...     print i, v
    ...
    0 {'ID': 1}