user1050619 user1050619 - 4 months ago 12
Python Question

Multiple if statement in list comprehension

I have a python list that needs to be converted to a tuple, I also need to add a additional check to check the list element type and convert them to tuple

for example:

row_data = ['map',[10,20]]

row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else d if type(d) is list else d for d in row_data)
print row_data


result
row_data == ('map', [10, 20])


Expected result

row_data == ('map', (10, 20))


Need to add multiple ifs within the list comprehension and each having its own output.

Answer

this should work -

row_data = ['map',[10,20]]

row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else tuple(d) if type(d) is list else d for d in row_data)
print(row_data)

Output: ('map', (10, 20))