I am trying to sort a list using a custom function. If the function has only one parameter, it is fine. I don’t know how to do if the function has 2 parameters.
For example, when the function has only one parameter.
def sort_by_well_range(col):
# col format is: avgDTS_1100_1200
a=col.split('_')[1:] # remove avgDTS string, keep only depth range
a=[float(col) for col in a] # convert string to float
middle_depth=mean(a)
# print(middle_depth)
return middle_depth
a=['avgDTS_1100_1200','avgDTS_900_1000','avgDTS_1300_1400','avgDTS_800_850']
b=sorted(a,key=sort_by_well_range,reverse=False)
['avgDTS_800_850', 'avgDTS_900_1000', 'avgDTS_1100_1200', 'avgDTS_1300_1400']
Now I am doing a function with 2 parameters like this, then I got an error, how to solve it? Thanks
def sort_by_well_range_1(col,start=1):
# col format is: avgDTS_1100_1200
a=col.split('_')[start:] # remove avgDTS string, keep only depth range
a=[float(col) for col in a] # convert string to float
middle_depth=mean(a)
# print(middle_depth)
return middle_depth
a=['influx_oil_1100_1200','influx_oil_900_1000','influx_oil_1300_1400','influx_oil_800_850']
b=sorted(a,key=sort_by_well_range_1(start=2),reverse=False)
---------------------------------------------------------------------------
TypeError
----> 2 b=sorted(a,key=sort_by_well_range_1(start=2),reverse=False)
3 b
TypeError: sort_by_well_range_1() missing 1 required positional argument: 'col'
>Solution :
In your first example you are correctly passing through sort_by_well_range function itself as the key argument, in the second example you are calling sort_by_well_range_1 and passing through the return value of that function as the key argument.
You need a function which takes one argument to pass as the key argument.
One way to do this is to wrap it in a small anonymous lambda function:
b = sorted(
a,
key=lambda x: sort_by_well_range_1(x, start=2),
reverse=False
)
There is also a helper function in functools called partial which will create a new function for you with certain parameters set which you could use:
from functools import partial
b = sorted(
a,
key=partial(sort_by_well_range_1, start=2),
reverse=False
)
This is more common if you need to re-use the same parameters to a function instead of declaring it over and over.