Stop calling things this
:X
[path for path, machine in zip(paths, machineIDs) if line == machine]
This also supposes paths
and machineIDs
are the same length.
If theyâre not, it can be mitigated by using izip_longest
from itertools:
from itertools import izip_longest as zipl
[path for path, machine in zipl(paths, machineIDs) if line == machine]
Now, Iâm expecting the machines Ids to be unique (machineIDs
could be a set).
Which means the resulting list will always either be empty (machine not found) or contain only one element.
If thatâs the case, instead of using a list comprehension, which will examine every element, you can use next()
and pass it a generator expression. Which is basically a list comprehension without the brackets:
from itertools import izip_longest as zipl
this = next(path for path, machine in zipl(paths, machineIDs) if line == machine)
this
will NOT be a list, but be the value of path
for wich line
matched the machine id.
If no match is found, it raises a stopIteration
. Which you can use in a try/except:
from itertools import izip_longest as zipl
try:
this = next(path for path, machine in zipl(paths, machineIDs) if line == machine)
except StopIteration:
logger.warn("no matching machine id found")
OR, you can pass next()
a second parameter, that it will return if no match is found.
from itertools import izip_longest as zipl
this = next((path for path, machine in zipl(paths, machineIDs) if line == machine), None)
if this is None:
logger.warn("no matching machine id found")
Note the added parentheses. Thatâs because with just one parameter, next()
figures out that itâs a generator expression. With another parameter, you need to help it out a bit.