1

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.

3 Answers 3

2

Using a comprehension:

sorted(data, key=lambda x: tuple(x[i] for i in fields))

Now fields can be arbitrary in size and values, provided x (inner list) has enough elements to not raise IndexError.

Sign up to request clarification or add additional context in comments.

Comments

1

This is overly complicated. Just use operator.itemgetter to create your key function.

import operator
def sort_cleaned_data(data, fields=None):
   return sorted(data, key=operator.itemgetter(*fields))

data = [
["John", 34, 2],
["Ashley", 30, 2],
["Peter", 28, 5],
["Bill", 29, 5],
["Jennifer", 65, 4],
["Laura", 33, 3]
]

sorted_data = sort_cleaned_data(data, fields=(2,1))
for d in sorted_data:
    print(d)

Output:

['Ashley', 30, 2]
['John', 34, 2]
['Laura', 33, 3]
['Jennifer', 65, 4]
['Peter', 28, 5]
['Bill', 29, 5]

Comments

0

You're making it much more complicated than it has to be:

def sort_cleaned_data(data, fields):
    return sorted(data, key=lambda x: (x[fields[0]], x[fields[1]]))


data = [
["John", 34, 2],
["Ashley", 30, 2],
["Peter", 28, 5],
["Bill", 29, 5],
["Jennifer", 65, 4],
["Laura", 33, 3]
]

sorted_data = sort_cleaned_data(data, fields=(2,1))
for d in sorted_data:
    print(d)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.