The basic objective is to sort a list of lists based on a field in the inner lists. So i have the below Python code for doing it:
import sys
def sort_cleaned_data(data, fields=None):
if not isinstance(fields, tuple):
raise ValueError("Argument to the function has to be a tuple")
else:
if all(list(map(lambda x:isinstance(x, int), fields))):
sorted_data = sorted(data, key=lambda x:(x[2],x[1]))
return sorted_data
else:
raise ValueError("All the values inside the fields tuple have to be integers")
data = [
["John", 34, 2],
["Ashley", 30, 2],
["Peter", 28, 5],
["Bill", 29, 5],
["Jennifer", 65, 4],
["Laura", 33, 3]
]
try:
sorted_data = sort_cleaned_data(data, fields=(2,1))
except ValueError as e:
print(e)
sys.exit(1)
for d in sorted_data:
print(d)
In the function sort_cleaned_data i have the fields tuple which contain the fields of the inner array on which to sort. So i have to dynamically generate the function : key=lambda x:(x[2],x[1]) based on the fields list.
I think this is the case of eval in Python but i am not sure how to do this . Can someone please help me here .
Many thanks in advance.