0

Suppose I have a list named L and two attribute dictionaries named arr1 and arr2, whose keys are the elements of the list L. Now I want to sort L in the following manner.

  1. L should be sorted in ascending order by virtue of the attribute values present in arr1.
  2. If two elements i and j of L have same attribute arr1, i,e, if arr1[i] and arr[j] are equal, then we should look for the attribute values in arr2.

To give an example, suppose

L=[0,1,2,3,4,5,6]
arr1={0:30,1:15,2:15,3:20,4:23,5:20,6:35}
arr2={0:6,1:8,2:6,3:17,4:65,5:65,6:34}

Sorted L should be [2,1,3,5,4,0,6], ordering between 1 and 2 is decided by arr2, so does the ordering between 3 and 5. Rest of the ordering are decided by arr1.

1 Answer 1

1

Simply use a tuple with the values from arr1 and arr2 as sort key:

L.sort(key=lambda x: (arr1[x], arr2[x]))
# [2, 1, 3, 5, 4, 0, 6]

This is different from your expected result in the ordering of 5 and 3, which would be consistent if the sort order would be descending based on arr2:

L.sort(key=lambda x: (arr1[x], -arr2[x]))
# [1, 2, 5, 3, 4, 0, 6]

But now the ordering of 1, 2 is different, your example doesn't seem to be ordered in a consistent way.

1
  • got it, thanks mate. I did a mistake in the in the final output. Commented Mar 16, 2016 at 12:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.