how to sort python list, using two elements in the list, instead of only using an x
- User
how to sort python list, using two elements in the list, instead of only using an x
Assistant
Here are a few ways to sort a Python list by two elements in each sublist:
- Using
keyparameter insorted()orlist.sort():
data = [[2, 5], [3, 4], [1, 1]] data.sort(key=lambda x: (x[0], x[1])) # Sorts by first element, then second element print(data) # [[1, 1], [2, 5], [3, 4]]- Using a custom compare function with
sorted()orlist.sort():
def compare(x, y): if x[0] < y[0]: return -1 elif x[0] > y[0]: return 1 elif x[1] < y[1]: return -1 elif x[1] > y[1]: return 1 return 0 data = [[2, 5], [3, 4], [1, 1]] data.sort(key=cmp_to_key(compare)) print(data) # [[1, 1], [2, 5], [3, 4]]- Using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.