W R W R - 1 year ago 109
Python Question

Python write nested loops with list comprehension for mult-variable function output

I have the following loop in Python 2.7.

pressure = []; cycle_flow = []; gauge_val = []
for element in readout_list:
if element.endswith('.dat'):
v1_2_3 = extract_sensor_values(element)

I am trying to write this as a list comprehension in one line. If the function
only returned one variable then I could easily use this list comprehension:

v1_2_3=[extract_sensor_values(element) for element in readout_list if element.endswith('.dat')]

However, I am not sure how to get three variables simultaneously from the function, using list comprehension. This seems simple when using multiple lines, but when I try to put it on one line it doesn't work.

Is it possible to return multiple function values in a list comprehension?

Answer Source

This isn't the sort of task that list-comprehensions were created to address. Each list comprehension in your code should produce exactly 1 list.

One thing you could do is use a list-comprehension to get the pressure, cycle_flow and guage_val triples and then use zip to "transpose" the result...

triples = [extract_sensor_values(element)
           for element in readout_list if element.endswith('.dat')]
pressure, cycle_flow, guage_val = zip(*triples)

A word of caution however -- This will leave you with tuple for the pressure, cycle_flow and guage_val variables (instead of list as was in your original code).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download